I felt like doing an algorithm and found this problem on leetcode
Given an array of integers, find two numbers such that they add up to a specific target num
Here is an Efficient Solution.
Time Complexity - O(n) and Space Complexity - O(1)
Sol: Will take two-pointer(start_pointer and end_pointer). Initially start_pointer point at the first index and end_pointer point to the last.
Add both the element (sum = array[start_pointer] + array[last_pointer]. After that check, if the sum > target element or not. If yes decrease the end_pointer else increase start_pointer. If sum = target, means you got the indexes.
public int[] twoSum(int[] numbers, int target) {
int[] arr = new int[2]; // to store result
int sum=0;
int start_pointer=0;
int end_pointer = (numbers.length)-1;
while(start_pointer<=end_pointer){
sum=numbers[start_pointer]+numbers[end_pointer];
if(sum>target)
end_pointer-=1;
else if(sum