Data Structures & Algorithms / Module 5: Algorithm patterns
Topic 5.1
Two pointers
Two markers moving through one array, ruling out one possibility at every step.
Watch: two markers move in from both ends. Each step one of them shifts, and one possibility is ruled out.
- moving now
- being checked
- finished / the result
- no longer used
Why you may throw a number away
The list is sorted. Start with the smallest (lo) and the largest (hi).
- If the sum is too big, the number at
hican't be in the answer. Its smallest possible partner is the number atlo, and even that is too much. So movehileft. - If it is too small, the number at
locan't be in the answer, for the same reason. Moveloright.
Every check rules out one number, so there are at most n − 1 checks. Trying every pair takes up to n(n − 1)/2.
Code, for programmersA pair with a given sum
function pairWithSum(sorted, target) {
let lo = 0, hi = sorted.length - 1;
while (lo < hi) {
const sum = sorted[lo] + sorted[hi];
if (sum === target) return [lo, hi];
if (sum > target) hi--; // hi is too big for any partner left
else lo++; // lo is too small for any partner left
}
return null;
}Other shapes of the same pattern
- Reversing an array in place: swap the left and right ends, then move inwards (Module 0).
- Checking a palindrome: compare the first letter with the last, the second with the second-to-last.
- Read and write pointers: one pointer reads every element, another writes the ones you keep. Used to remove duplicates from a sorted array without a new array.
- Merging two sorted lists: one pointer in each list, as in merge sort.
Quiz
In a sorted list, lo + hi is bigger than the target. What do you do?
At most how many checks does two pointers need on n numbers?
The list isn't sorted. The fastest way to find a pair with a given sum?
0 of 3 answered.