Problem Summary

You’re given an array of integers (positive + negative).

You repeatedly:

Continue until no more operations can be done.

Key Insight

This behaves exactly like a collision problem (similar to asteroid collision 🚀).

Why stack?
Because:

Core Idea (Stack Approach)

We process elements one by one:

Rules:

Let:

top = stack.peek()
curr = current element

If signs are opposite:

If signs are same:

Example Walkthrough

Input:

arr = [10, -5, -8, 2, -5]

Step-by-step:

Output:

[10]

Another Example

arr = [5, -5, -2, -10]

Output:

[-2, -10]

Algorithm

Java Code

import java.util.*;

class Solution {
    public ArrayList<Integer> reducePairs(int[] arr) {
        Stack<Integer> stack = new Stack<>();

        for (int num : arr) {
            boolean removed = false;

            while (!stack.isEmpty() && stack.peek() * num < 0) {
                int top = stack.peek();

                if (Math.abs(top) > Math.abs(num)) {
                    removed = true;
                    break;
                } 
                else if (Math.abs(top) < Math.abs(num)) {
                    stack.pop();
                } 
                else {
                    stack.pop();
                    removed = true;
                    break;
                }
            }

            if (!removed) {
                stack.push(num);
            }
        }

        return new ArrayList<>(stack);
    }
}

Complexity

Key Takeaways

Same pattern appears in: