VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reduce-array-by-replacing-adjacent-opposite-sign-pairs-with-their-absolute-maximum/

⇱ Opposite Sign Pair Reduction - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Opposite Sign Pair Reduction

Last Updated : 24 Apr, 2026

Given an array arr[] of size n, the task is to find the final array by repeatedly performing the following operations from left to right and check, If two adjacent elements have opposite signs:

  • Remove both elements and insert the element with the larger absolute value, along with its sign.
  • If both elements have the same absolute value, remove both without inserting anything.

Examples:

Input: arr[] = [10, -5, -8, 2, -5]
Output: [10]
Explanation:
At Index 0 : Element 10 has positive sign.
At Index 1 : -5  has lesser absolute value than 10. Replace both of them with 10.
At Index 2 : -8  has lesser absolute value than 10. Replace both of them with 10.
At Index 3 : 2 has positive sign. So it will be in the array.
At Index 4 : -5  has greater absolute value than 2. Replace both of them with 5.
Now -5  has lesser absolute value than 10. Replace both of them with 10.

Input: arr[] = [5, -5, -2, -10]
Output: [-2, -10]
Explanation: 1st and 2nd element gets discarded because both elements have same values but opposite sign. 3rd and 4th elements have same sign. So, both will be in the array.

[Naive Approach] Iterative Method - O(n^2) Time and O(1) Space

The idea is to repeatedly scan the array from left to right and resolve only the first adjacent opposite sign pair by keeping the element with larger absolute value or removing both if equal. After each modification, restart the scan from the beginning since new adjacent pairs may form. Continue this process until no more such pairs exist in the array.

Dry run for arr[] = [10, -5, -8, 2, -5]:

  1. For i = 0, elements 10 and -5 have opposite signs and |10| > |−5|, so keep 10, Array becomes [10, -8, 2, -5]
  2. For i = 0, elements 10 and -8 have opposite signs and |10| > |−8|, so keep 10, Array becomes [10, 2, -5]
  3. For i = 0, elements 10 and 2 have same sign, so move ahead
  4. For i = 1, elements 2 and -5 have opposite signs and |−5| > |2|, so keep -5, Array becomes [10, -5]
  5. For i = 0, elements 10 and -5 have opposite signs and |10| > |−5|, so keep 10, Array becomes [10]
  6. No more pairs exist, process stops

Final array is [10]

[Expected Approach] Using Stack - O(n) Time and O(n) Space

The idea is to traverse the array and use a stack to store elements. For each element, resolve collisions with the stack top whenever they have opposite signs, by removing the smaller absolute value or both if equal. Continue this process until no conflict remains, then push the current element. The stack finally contains the valid elements after handling all adjacent opposite sign interactions.



Output
10 
Comment