Core patterns
The patterns below are used a lot in coding interview problems.
This lesson shows the main idea of each one on a simple example. In real problems, the same patterns are often combined or used in less obvious ways, so the best way to learn them is to practise them on problems.
Two pointers. O(n) time.
Two pointers traverse an array with one loop and two indexes instead of one, so elements from different places are handled together in a single pass instead of two nested loops.
Example
Given an array, reverse it in place.
Start the left index at the first element and the right index at the last one.
Swap their elements, then move left to the right and right to the left, until they meet.
Binary search. O(log n) time.
Binary search checks a condition on the middle element and decides which half can hold the answer, so the other half is cut off. Halving the range at every step takes steps.
Example
Given a sorted array and a target, find the index of the target.
Compare the middle element of the range with the target. If it is less than the target, the target can only be in the right half, and if it is greater, only in the left half.
Prefix sum. O(n) time.
A prefix sum is the sum of the elements before an index. Keeping it for every index gives the sum of any part of the array with one subtraction.
Example
Given an array, find the index where the sum of the elements on its left equals the sum of the elements on its right.
Keep the sum of the elements before the current index as left, adding the current element after each step.
The sum on the right is then total - left - nums[i].
Sliding window. O(n) time.
A sliding window is a range of consecutive elements that moves through the array.
Instead of computing the whole range again after every move, the result is updated with the element that enters and the element that leaves.
Example
Given an array and a number k, find the sum of every k consecutive elements.
Sum the first elements, then slide the window one element at a time, adding the element that enters and subtracting the element that leaves.