Open In App

Find final Array by removing adjacent elements with different sign

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of positive and negative integers. If two adjacent elements have different signs, remove them. Find the final array if the operation is performed repeatedly.

Examples:

Input: arr[] = {4, 2, -2, 1}
Output: 4 1
Explanation: As at indices 1 and 2, 2 and -2 have different sign, they are removed. And the  the final array is: 4 1.

Input: arr[] = {2, -2, 1, -1}
Output: []
Explanation: As at indices 0 and 1, 2 and -2 have different sign, so they are removed. Now the array is 1 -1.Now 1 and -1 are also removed as they have different sign. So the final array is empty.

Approach: The problem can be solved based on the following idea:

Create a vector and keep storing the elements if the current element and the last inserted element in the vector have the same sign. Otherwise, remove the last inserted element from the vector.

Follow the steps mentioned below to implement the idea:

  • Define a vector of integers (say ans[]) to store the final state of the array.
  • Start iterating the array arr[]:
    • If the last element in ans[] has the same sign as the current element of arr[], then push the current element into ans[].
    • If the last element in ans[] does not have the same sign as the current element, then pop the last element of the answer vector.
  • Return ans[] as the required final array.

Below is the implementation of the above approach:  

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the final array
vector<int> makeBeautiful(vector<int> arr)
{
    vector<int> ans;
    for (int i = 0; i < arr.size(); i++) {
 
        // If the size of ans vector is 0,
        // or last element in the ans
        // vector has same sign as the
        // arr[i] then push arr[i] into ans
        if (ans.size() == 0
            || ans.back() >= 0 && arr[i] >= 0
            || ans.back() < 0 && arr[i] < 0)
            ans.push_back(arr[i]);
 
        // If the last element in the ans
        // vector does not have same sign
        // as the arr[i] then pop the
        // last element of ans.
        else
            ans.pop_back();
    }
 
    // Return the result
    return ans;
}
 
// Driver code
int main()
{
    vector<int> arr = { 4, 2, -2, 1 };
    vector<int> res;
 
    // Function call
    res = makeBeautiful(arr);
 
    for (int x : res)
        cout << x << " ";
    return 0;
}


Java




import java.util.*;
 
public class Main {
    // Function to find the final array
  public static List<Integer>makeBeautiful(List<Integer> arr)
    {
        List<Integer> ans = new ArrayList<Integer>();
        for (int i = 0; i < arr.size(); i++) {
 
            // If the size of ans list is 0,
            // or last element in the ans
            // list has same sign as the
            // arr[i] then add arr[i] into ans
            if (ans.size() == 0
                || ans.get(ans.size() - 1) >= 0
                       && arr.get(i) >= 0
                || ans.get(ans.size() - 1) < 0
                       && arr.get(i) < 0)
                ans.add(arr.get(i));
 
            // If the last element in the ans
            // list does not have same sign
            // as the arr[i] then remove the
            // last element of ans.
            else
                ans.remove(ans.size() - 1);
        }
 
        // Return the result
        return ans;
    }
 
   // Driver code
   public static void main(String[] args)
    {
        List<Integer> arr = new ArrayList<Integer>(
            Arrays.asList(4, 2, -2, 1));
        List<Integer> res;
 
        // Function call
        res = makeBeautiful(arr);
 
        for (int x : res)
            System.out.print(x + " ");
    }
}


Python3




# python code to implement the approach
 
def makeBeautiful(arr):
    ans = []
    for i in range(len(arr)):
        # If the size of ans list is 0, or the last element in the ans
        # list has the same sign as arr[i], then append arr[i] to ans
        if len(ans) == 0 or (ans[-1] >= 0 and arr[i] >= 0) or (ans[-1] < 0 and arr[i] < 0):
            ans.append(arr[i])
         
        # If the last element in the ans list does
        # not have the same sign as arr[i],
        # then remove the last element from ans
        else:
            ans.pop()
     
    # Return the result
    return ans
 
 
# Driver code
arr = [4, 2, -2, 1]
 
# Function call
res = makeBeautiful(arr)
 
# Printing the result
for x in res:
    print(x, end=" ")


C#




// C# code to implement the approach
 
using System;
using System.Collections.Generic;
 
public class Solution
{
    // Function to find the final array
    public static List<int> MakeBeautiful(List<int> arr)
    {
        List<int> ans = new List<int>();
        for (int i = 0; i < arr.Count; i++)
        {
            // If the size of ans list is 0,
            // or last element in the ans
            // list has the same sign as the
            // arr[i], then add arr[i] into ans
            if (ans.Count == 0 || ans[ans.Count - 1] >= 0 && arr[i] >= 0 || ans[ans.Count - 1] < 0 && arr[i] < 0)
                ans.Add(arr[i]);
 
            // If the last element in the ans
            // list does not have the same sign
            // as the arr[i], then remove the
            // last element of ans.
            else
                ans.RemoveAt(ans.Count - 1);
        }
 
        // Return the result
        return ans;
    }
 
    // Entry point of the program
    public static void Main(string[] args)
    {
        List<int> arr = new List<int>() { 4, 2, -2, 1 };
        List<int> res;
 
        // Function call
        res = MakeBeautiful(arr);
 
        foreach (int x in res)
            Console.Write(x + " ");
    }
}


Javascript




// Function to find the final array
function makeBeautiful(arr) {
    let ans = [];
    for (let i = 0; i < arr.length; i++) {
         
        // If the size of ans vector is 0,
        // or last element in the ans
        // vector has same sign as the
        // arr[i] then push arr[i] into ans
        if (ans.length === 0 || ans[ans.length - 1] >= 0 && arr[i] >= 0 || ans[ans.length - 1] < 0 && arr[i] < 0) {
            ans.push(arr[i]);
        }
         
        // If the last element in the ans
        // vector does not have same sign
        // as the arr[i] then pop the
        // last element of ans.
        else {
            ans.pop();
        }
    }
     
    // Return the result
    return ans;
}
 
// Driver code
let arr = [4, 2, -2, 1];
let res = makeBeautiful(arr);
for (let x of res) {
    console.log(x + " ");
}


Output

4 1 







Time Complexity: O(N)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads