Given an array, find the first pair whose sum is equal to zero?
Input = [-5, -4, -3, -2, 0, 2, 4, 6, 8].
Output = [-4, 4].
Solution:
Check the given array is sorted or not. If not sort the array.
Approach 1:
We need to traverse the each and every element of the array and compare it with other elements of the array.
We have to apply two loops in it. The first loop (outer one) will start traversing from 0 index of the array and the second loop (inner one ) will start traversing from 1 index of the array. If the sum of 0th index of array and 1st index of array is equal to ZERO then return the pair.
By using this approach we will get Quadratic Time Complexity O(n²).
Approach 2:
Let's assume to variables and assign them with 0 index and last index of array:
- let left = 0;
- let right = array.length - 1 ; We need to run a single loop in which we will check if the sum of the left index value and right index value of the given array is equal to Zero, then return that Pair. If sum (left, right) > 0 then decrement the right variable (right--). If sum (left, right) < 0 then increment the left variable(left++). By this approach we can get the Pair of Sum Zero in only one loop.
By using this approach we will get Linear Time Complexity O(n).
Top comments (0)