![]() |
VOOZH | about |
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:
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.
Table of Content
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]:
Final array is [10]
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.
10