Topic · 5 patterns
Arrays & Two Pointers patterns
Most array questions are about not rescanning. Each of these five patterns turns an O(n²) scan into one or two passes: two pointers and sliding window move indices that never go back, prefix sums and difference arrays precompute running totals so any range costs O(1), and cyclic sort uses the values themselves as positions when they run from 1 to n.
The patterns
Two Pointers
O(n) / O(1)
Walk two indices toward each other (or same-direction) so each step discards a whole branch of possibilities.
Spot it: Sorted input (or sorting is free): find a pair/triplet with a target sum or best value, in-place dedupe/partition, or palindrome check.
Sliding Window
O(n)
Expand the right edge; shrink the left only while the window violates the rule. Track the best as you go.
Spot it: Longest/shortest/count of a contiguous subarray or substring under a monotone rule (sum, ≤k distinct, no repeats), or a fixed size k.
Learn first: Two Pointers
Prefix Sum
O(n)
Store cumulative sums; the sum of any range is a subtraction. Pair with a hashmap of seen prefixes to count subarrays.
Spot it: Many range-sum queries on a static array, or count subarrays with sum/xor/mod = k (negatives OK), or balance problems (map 0 to -1).
Cyclic Sort
O(n) / O(1)
Each value's correct index is the value itself — swap numbers home in one pass, then scan for the one out of place.
Spot it: n numbers in range 1..n (or 0..n); find the missing, duplicate, or first missing positive in O(n) time and O(1) space.
Difference Array & Line Sweep
O(n log n)
Mark +1 at each start and −1 just past each end, then sweep a prefix sum to get the value at every position.
Spot it: Many range-add updates with reads only at the end, or max overlap at a point: bookings, car pooling, calendars, flowers in bloom.
Learn first: Prefix Sum
Which one? Match the signal
| If the problem says | Reach for |
|---|---|
| Sorted array; find a pair / triplet hitting a target, or shrink from both ends | Two Pointers |
| Contiguous subarray/substring asked to be longest/shortest/max/min under a constraint | Sliding Window |
| "Subarray sum equals k" / "divisible by k", or many range-sum queries | Prefix Sum + HashMap |
| Array holds n numbers from a 1..n range; find missing / duplicate / first-missing-positive | Cyclic Sort |
| Many range increments, or count overlapping events at a point (bookings, car pool) | Difference Array / Sweep |
Easy to confuse
Subarray Sum Equals K looks like Sliding Window, but it’s Prefix Sum
Negative numbers make window validity non-monotone; count prefix pairs with a hash map.
Subarray Sums Divisible by K looks like Sliding Window, but it’s Prefix Sum
Divisibility is not monotone in window size; key prefix sums by residue.
Shortest Subarray with Sum at Least K looks like Sliding Window, but it’s Monotonic Deque
Negatives break shrinking; keep a monotone deque of prefix sums.
Find the Duplicate Number looks like Cyclic Sort, but it’s Fast & Slow Pointers
Array must not be modified and O(1) space: values form a functional graph whose cycle entry is the duplicate.
Reverse Pairs looks like Two Pointers, but it’s Divide and Conquer (merge-sort counting)
Pairs i < j with a[i] > 2a[j] are counted across merge-sort halves (or with a BIT).
Sum of Subarray Minimums looks like Sliding Window, but it’s Monotonic Stack
No window condition; each element's contribution span comes from previous/next smaller.
Used together
Prefix Sum + Hash Map / Hash Set Lookup
When: count/longest subarrays with sum (or mod, or balance) equal to a target, negatives allowed. With negative numbers no window is monotone; the pair view plus a lookup counts all subarrays in O(n).
Sliding Window + Hash Map / Hash Set Lookup
When: longest/shortest substring with distinct/at-most-K/covers-all-chars condition. Validity depends on counts inside the window, which must update in O(1) per move.
Sliding Window + Monotonic Deque
When: subarray where max - min <= limit, or window extreme queries. Validity depends on window max-min, which a counter cannot maintain under deletions.
When: shortest subarray with sum >= K when values can be negative; max subarray sum with length in [a, b]. Negative values break window monotonicity; on prefix sums, dominated left ends can be discarded.
Two Pointers
- Valid PalindromeEasy
- Two Sum II - Input Array Is SortedMedium
Sliding Window
- Maximum Average Subarray IEasy
- Longest Substring Without Repeating CharactersMedium
Prefix Sum
- Running Sum of 1d ArrayEasy
- Range Sum Query - ImmutableEasy
Cyclic Sort
- Missing NumberEasy
- Find All Numbers Disappeared in an ArrayEasy
Difference Array & Line Sweep
- Corporate Flight BookingsMedium
Further reading
- Two PointersUSACO Guide
Clean explanation plus graded problems for two pointers and sliding window.
- Prefix SumsUSACO Guide
1D/2D prefix sums with problems; foundation for difference arrays.
- More on Prefix Sums (difference arrays)USACO Guide
Difference arrays, prefix minimum and range-update tricks.
- Array cheatsheetTech Interview Handbook
Interview corner cases, techniques and must-do problem list for arrays.
- NeetCode RoadmapNeetCode
Pattern-ordered problem tree with a short video per problem; best interview-first path.
- Array and String explore cardLeetCode
Guided basics with in-browser problems; good warmup before pattern drilling.