Easy · Two Pointers
Understand → Visualise → Practice.
When an array is sorted, you can find a pair with a given sum without any extra memory.
Start one pointer at each end. If the sum is too small, move the left pointer right; if it is too big, move the right pointer left.
L at the first index, R at the last.
nums[L] + nums[R] against the target.
Too small → L++. Too big → R−−. Equal → done.
O(n) time and O(1) space. Sorting first would cost O(n log n) if the input were not sorted.
This only works because the array is sorted; on unsorted data use the hash-map approach.
Read the full guides first: Big-O and Complexity, Arrays and Dynamic Arrays, Prefix Sums and Difference Arrays.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.