Skip to content
Related Articles

Related Articles

Find the resulting output array after doing given operations

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Expert
  • Last Updated : 21 Jun, 2022

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++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the remaining numbers
vector<int> remainingNumbers(vector<int>&
                             integers)
{
 
    // Size of the array
    int n = integers.size();
 
    // Initialize the stack
    stack<int> s;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
        if (integers[i] > 0 || s.empty()) {
            s.push(integers[i]);
        }
        else {
            while (!s.empty() and s.top() > 0
                   and s.top() <
                   abs(integers[i])) {
                s.pop();
            }
            if (!s.empty()
                and s.top() ==
                abs(integers[i])) {
                s.pop();
            }
            else if (s.empty() ||
                     s.top() < 0) {
                s.push(integers[i]);
            }
        }
    }
 
    // Finally we are returning the elements
    // which remains in the stack.
    // we have to return them in reverse order.
    vector<int> res(s.size());
    for (int i = (int)s.size() - 1; i >= 0;
         i--) {
        res[i] = s.top();
        s.pop();
    }
    return res;
}
 
// Driver Code
int main()
{
 
    vector<int> integers = { 3, -2, 4 };
    vector<int> ans =
        remainingNumbers(integers);
 
    for (int x : ans) {
        cout << x << " ";
    }
 
    return 0;
}


Java




// Java program for the above approach
 
import java.util.Stack;
 
class GFG {
 
    // Function to find the remaining numbers
    static int[] remainingNumbers(int[] integers)
    {
 
        // Size of the array
        int n = integers.length;
 
        // Initialize the stack
        Stack<Integer> s = new Stack<Integer>();
 
        // Traverse the array
        for (int i = 0; i < n; i++) {
            if (integers[i] > 0 || s.empty()) {
                s.push(integers[i]);
            }
            else {
                while (!s.empty() && s.peek() > 0
                       && s.peek()
                              < Math.abs(integers[i])) {
                    s.pop();
                }
                if (!s.empty()
                    && s.peek() == Math.abs(integers[i])) {
                    s.pop();
                }
                else if (s.empty() || s.peek() < 0) {
                    s.push(integers[i]);
                }
            }
        }
 
        // Finally we are returning the elements
        // which remains in the stack.
        // we have to return them in reverse order.
        int[] res = new int[s.size()];
        for (int i = s.size() - 1; i >= 0; i--) {
            res[i] = s.peek();
            s.pop();
        }
        return res;
    }
 
    // Driver Code
    public static void main(String args[])
    {
 
        int[] integers = { 3, -2, 4 };
        int[] ans = remainingNumbers(integers);
 
        for (int x : ans) {
            System.out.print(x + " ");
        }
    }
}
 
// This code is contributed by Lovely Jain


Python3




# python3 program for the above approach
 
# Function to find the remaining numbers
 
 
def remainingNumbers(integers):
 
        # Size of the array
    n = len(integers)
 
    # Initialize the stack
    s = []
 
    # Traverse the array
    for i in range(0, n):
        if (integers[i] > 0 or len(s) == 0):
            s.append(integers[i])
 
        else:
            while (len(s) != 0 and s[len(s) - 1] > 0
                   and s[len(s) - 1] < abs(integers[i])):
                s.pop()
 
            if (len(s) != 0
                and s[len(s) - 1] ==
                    abs(integers[i])):
                s.pop()
 
            elif (len(s) == 0 or
                  s[len(s) - 1] < 0):
                s.append(integers[i])
 
        # Finally we are returning the elements
        # which remains in the stack.
        # we have to return them in reverse order.
    res = [0 for _ in range(len(s))]
    for i in range(len(s) - 1, -1, -1):
        res[i] = s[len(s) - 1]
        s.pop()
 
    return res
 
 
# Driver Code
if __name__ == "__main__":
 
    integers = [3, -2, 4]
    ans = remainingNumbers(integers)
 
    for x in ans:
        print(x, end=" ")
 
    # This code is contributed by rakeshsahni


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
   
  // Function to find the remaining numbers
  static List<int> remainingNumbers(List<int> integers)
  {
 
    // Size of the array
    int n = integers.Count;
 
    // Initialize the stack
    Stack<int> s = new Stack<int>();
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
      if (integers[i] > 0 || s.Count == 0) {
        s.Push(integers[i]);
      }
      else {
        while (s.Count != 0 && s.Peek() > 0
               && s.Peek()
               < Math.Abs(integers[i])) {
          s.Pop();
        }
        if (s.Count != 0
            && s.Peek() == Math.Abs(integers[i])) {
          s.Pop();
        }
        else if (s.Count == 0 || s.Peek() < 0) {
          s.Push(integers[i]);
        }
      }
    }
 
 
    // Finally we are returning the elements
    // which remains in the stack.
    // we have to return them in reverse order.
    List<int> res = new List<int>(new int [s.Count]);
 
    for (int i = (int)s.Count - 1; i >= 0; i--) {
      res[i] = s.Peek();
      s.Pop();
    }
    return res;
  }
 
  // Driver Code
  public static void Main()
  {
 
    List<int> integers = new List<int>() { 3, -2, 4 };
    List<int> ans = remainingNumbers(integers);
 
    foreach(int x in ans) { Console.Write(x + " "); }
  }
}
 
// This code is contributed by ukasp.


Javascript




  <script>
      // JavaScript code for the above approach
 
      // Function to find the remaining numbers
      function remainingNumbers(
          integers) {
 
          // Size of the array
          let n = integers.length;
 
          // Initialize the stack
          let s = [];
 
          // Traverse the array
          for (let i = 0; i < n; i++) {
              if (integers[i] > 0 || s.length == 0) {
                  s.push(integers[i]);
              }
              else {
                  while (s.length != 0 && s[s.length - 1] > 0
                      && s[s.length - 1] <
                      Math.abs(integers[i])) {
                      s.pop();
                  }
                  if (s.length != 0
                      && s[s.length - 1] ==
                      Math.abs(integers[i])) {
                      s.pop();
                  }
                  else if (s.length == 0 ||
                      s[s.length - 1] < 0) {
                      s.push(integers[i]);
                  }
              }
          }
 
          // Finally we are returning the elements
          // which remains in the stack.
          // we have to return them in reverse order.
          let res = new Array(s.length);
          for (let i = s.length - 1; i >= 0;
              i--) {
              res[i] = s[s.length - 1];
              s.pop();
          }
          return res;
      }
 
      // Driver Code
 
 
      let integers = [3, -2, 4];
      let ans =
          remainingNumbers(integers);
 
      for (let x of ans) {
          document.write(x + " ");
      }
 
 
// This code is contributed by Potta Lokesh
  </script>


 
 

Output

3 4 

 

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

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!