Find the resulting output array after doing given operations
Last Updated :
23 Jul, 2025
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>
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);
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem