An interactive visualization of the two-pointer technique on a sorted array. Watch how the left and right pointers converge to find two numbers that add up to the target.
Two Pointers LeetCode 167 โ Easynumbers that is already sorted in non-decreasing order,
find two numbers such that they add up to a specific target number.index1 and index2,
added by one (1-indexed) as an integer array [index1, index2].fun twoSum(numbers: IntArray, target: Int): IntArray { var left = 0; var right = numbers.size - 1 while (left < right) { val currentSum = numbers[left] + numbers[right] if (currentSum == target) { // found it! return intArrayOf(left + 1, right + 1) } else if (currentSum < target) { // need bigger sum left++ } else { // need smaller sum right-- } } return intArrayOf() // no solution}
Because the array is sorted, we can use two pointers starting from opposite ends. If the current sum is too small, moving the left pointer right increases the sum. If the current sum is too large, moving the right pointer left decreases the sum. This guarantees we find the answer in a single pass without needing a hash map.
left = 0 (start of array), right = len(numbers) - 1 (end of array)current_sum = numbers[left] + numbers[right][left + 1, right + 1] (1-indexed)left pointer right (left += 1)right pointer left (right -= 1)
Each pointer moves at most n steps total, and we use only two variables for the pointers โ no extra data structures needed.