Open In App

Find the resulting output array after doing given operations

Improve
Improve
Like Article
Like
Save
Share
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++




// 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)

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




// 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)
{
 
    int n = integers.size();
    vector<int> st;
    for (int i = 0; i < n; i++) {
        if (integers[i] > 0 || st.empty()) {
            st.push_back(integers[i]);
        }
        else {
            while (!st.empty() and st.back() > 0
                   and st.back() < abs(integers[i])) {
                st.pop_back();
            }
            if (!st.empty()
                and st.back() == abs(integers[i])) {
                st.pop_back();
            }
            else if (st.empty() || st.back() < 0) {
                st.push_back(integers[i]);
            }
        }
    }
 
    return st;
}
 
// 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.*;
 
public class Main {
    // Function to find the remaining numbers
    public static ArrayList<Integer>
    remainingNumbers(ArrayList<Integer> integers)
    {
 
        int n = integers.size();
        ArrayList<Integer> st = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (integers.get(i) > 0 || st.isEmpty()) {
                st.add(integers.get(i));
            }
            else {
                while (!st.isEmpty()
                       && st.get(st.size() - 1) > 0
                       && st.get(st.size() - 1)
                              < Math.abs(integers.get(i))) {
                    st.remove(st.size() - 1);
                }
                if (!st.isEmpty()
                    && st.get(st.size() - 1)
                           == Math.abs(integers.get(i))) {
                    st.remove(st.size() - 1);
                }
                else if (st.isEmpty()
                         || st.get(st.size() - 1) < 0) {
                    st.add(integers.get(i));
                }
            }
        }
 
        return st;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        ArrayList<Integer> integers
            = new ArrayList<>(Arrays.asList(3, -2, 4));
        ArrayList<Integer> ans = remainingNumbers(integers);
 
        for (int x : ans) {
            System.out.print(x + " ");
        }
    }
}


Python3




# Python3 program for the above approach
from typing import List
 
# Function to find the remaining numbers
 
 
def remainingNumbers(integers: List[int]) -> List[int]:
    n = len(integers)
    st = []
 
    for i in range(n):
        if (integers[i] > 0 or not st):
            st.append(integers[i])
        else:
            while (st and st[-1] > 0 and st[-1] < abs(integers[i])):
                st.pop()
            if (st and st[-1] == abs(integers[i])):
                st.pop()
            elif (not st or st[-1] < 0):
                st.append(integers[i])
 
    return st
 
 
# Driver Code
integers = [3, -2, 4]
ans = remainingNumbers(integers)
 
for x in ans:
    print(x, end=' ')


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)
    {
        int n = integers.Count;
        List<int> st = new List<int>();
 
        for (int i = 0; i < n; i++) {
            if (integers[i] > 0 || st.Count == 0) {
                st.Add(integers[i]);
            }
            else {
                while (st.Count != 0 && st[st.Count - 1] > 0
                       && st[st.Count - 1]
                              < Math.Abs(integers[i])) {
                    st.RemoveAt(st.Count - 1);
                }
                if (st.Count != 0
                    && st[st.Count - 1]
                           == Math.Abs(integers[i])) {
                    st.RemoveAt(st.Count - 1);
                }
                else if (st.Count == 0
                         || st[st.Count - 1] < 0) {
                    st.Add(integers[i]);
                }
            }
        }
 
        return st;
    }
 
    // Driver Code
    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 + " "); }
    }
}


Javascript




// JavaScript program to implement the above approach
function remainingNumbers(integers) {
    let n = integers.length;
    let st = [];
 
    for (let i = 0; i < n; i++) {
 
        // If element is positive or stack is empty, push it into stack
        if (integers[i] > 0 || st.length == 0) {
            st.push(integers[i]);
        }
 
        // If element is negative, check if absolute of
        // top of stack is less than or equal to it.
        // If yes, pop the top element.
        // If not, push the element into stack
        else {
            while (st.length > 0 && st[st.length - 1] > 0 &&
                st[st.length - 1] < Math.abs(integers[i])) {
                st.pop();
            }
 
            // If top element is same as absolute of current
            // element, pop the top element.
            if (st.length > 0 && st[st.length - 1] == Math.abs(integers[i])) {
                st.pop();
            }
 
            // If stack is empty or top element is negative,
            // push the current element into stack.
            else if (st.length == 0 || st[st.length - 1] < 0) {
                st.push(integers[i]);
            }
        }
    }
 
    return st;
}
 
// Driver Code
let integers = [3, -2, 4];
let ans = remainingNumbers(integers);
 
// Print the remaining numbers
console.log(ans);


Output

3 4 

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

 



Last Updated : 06 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads