Given a sorted array of integers and a number N.
Find out all pairs of numbers of the array whose sum is N.
Simply find out all integers a, b of array such that a + b = N
Solution :
Take two variables that holds the value of First and Last index of array.
Loop while First < Last:
Now sum value stored in First and Last index of the array.
If sum is greater than N
decrease Last by 1.
If sum is less than N,
increase First by 1.
If sum is equal to N,
print values stored at First and Last index.
Decrease Last by 1 and Increase First by 1.
Complexities :
- Time : O(N)
- Space : O(1)
No comments:
Post a Comment