Arrays And Strings
Two Pointers
Move left and right pointers inward on a sorted array to find a pair sum with linear time and constant auxiliary space.
O(n) time / O(1) space
target: 10sum: -
Index 0L
5Index 1
5Index 2
5Index 3
6Index 4
8Index 5R
11Time
O(n)
Space
O(1)
Step Note
Sort the values, then place one pointer at each end.
function twoPointerPairSum(values: number[], target: number) {
const array = [...values].sort((a, b) => a - b)
let left = 0
let right = array.length - 1
while (left < right) {
const sum = array[left] + array[right]
if (sum === target) return [left, right]
if (sum < target) {
left++
} else {
right--
}
}
return null
}