Open In App

Find the resulting output array after doing given operations

Last Updated : 06 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array integers[] of integers of size N. Find the resulting output array after doing some operations: 

  • If the (i-1)th element is positive and ith element is negative  then :
    • If the absolute of (i)th is greater than (i-t)th, remove all the contiguous positive elements from left having absolute value less than ith.
    • If the absolute of (i)th is smaller than (i-t)th, remove this element.
    • If the absolute of (i)th is equal to (i-1)th then remove both the elements.

Examples:

Input: integers[] = {3, -2, 4}
Output: 3 4
Explanation: The first number will cancel out the second number. 
Hence, the output array will be {3,4}. 

Input: integers[] = {-2, -1, 1, 2}
Output: -2 -1 1 2
Explanation: After a positive number, negative number is not added. 
So every number would be present in the output array

 

Approach: Ignore numbers of the same sign irrespective of their magnitude. So the only case that we have to consider is when the previous element is of positive magnitude and the next element is of negative magnitude We can use stack to simulate the problem. Follow the steps below to solve the problem:

  • Initialize the stack s[].
  • Iterate over the range [0, N) using the variable i and perform the following tasks:
    • If integers[i] is greater than 0 or s[] is empty, then push integers[i] into the stack s[].
    • Otherwise, traverse in a while loop till s is not empty and s.top() is greater than 0 and s.top() is less than abs(integers[i]) and perform the following tasks:
      • Pop the element from the stack s[].
    • If s is not empty and s.top() equals abs(integers[i]) then pop from the stack s[].
    • Else if s[] is empty or s.top() is less than 0 then push integers[i] into the stack s[].
  • Initialize the vector res[s.size()] to store the result.
  • Iterate over the range [s.size()-1, 0] using the variable i and perform the following tasks:
    • Set res[i] as s.top() and pop from the stack s[].
  • After performing the above steps, print the value of res[] as the answer.

Below is the implementation of the above approach.

C++
Java Python3 C# JavaScript

 
 


Output
3 4 


 

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

A little bit optimized approach:

We can avoid the last reverse operation which takes O(N) time by using vector instead of stack

Below is the implementation of the same

C++
Java Python3 C# JavaScript

Output
3 4 

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


 


Next Article
Article Tags :
Practice Tags :

Similar Reads