As explained in the Google video that links Alexander G to , use two array indexes. Initialize the first element (0) and the second to the last element ( sortedArray.length - 1 ). In a loop, check the sum of two elements in two indices. If the amount is the number you were looking for, you did. If it is too high, you need to find a smaller number in one of the indices; move the right index one step to the left (since the array is sorted, this is the right way). If, on the other hand, the amount you received was too low, move the left pointer to the right to get a higher first addition. When the two indexes meet, if you still have not found the amount you were looking for, it is not. At this point, you ran n - 1 times through the loop, so the algorithm works in O (n).
We must first check the precondition that the array is indeed sorted. This can also be done in O (n), so doing this does not violate any requirements.
The algorithm may need to be refined if you need to find all possible pairs of numbers that give the desired amount, and not just one pair.
Is this answer redundant when video calling has already spoken about it? Firstly, my explanation is shorter, so if this is enough, you're fine. Most importantly, if the video is deleted or just moved to a different URL, my answer will still be here.
source share