Two Pointers & Sliding Window
- Recognize the signals for converging pointers, read/write pointers and sliding windows
- Write the variable-size window template from memory and adapt it to "longest" and "shortest" variants
- Prove why a pointer move is safe (the elimination argument) instead of hoping
- Know when windows fail (negative numbers) and what to use instead
- Apply time-based windows to velocity checks and rate limiting
TL;DR
- Converging pointers on sorted data: compare
a[l] + a[r]to the target and discard the side that cannot be part of any answer. O(n), O(1) space. - Read/write pointers compact or partition a slice in place (remove duplicates, drop zero amounts) — O(n), stable.
- Sliding window: expand
rightevery step; while the window is invalid, shrinkleft; record the answer when valid. Each index enters and leaves once → O(n). - The window needs monotonicity: shrinking a window must never make it "more invalid". Sums with negative numbers break this → use prefix sum + hash map.
- Exactly K = atMost(K) − atMost(K − 1) turns awkward "exactly" constraints into two easy windows.
- Time-based windows (last 60 s per card) are the same idea with timestamps — the basis of fraud velocity rules and sliding-log rate limiters.
When to reach for it
- Input is sorted (or you may sort it) and you need a pair/triplet with a target sum or difference → converging pointers.
- "Remove / move / partition in place", "return the new length" → read/write pointers.
- "Longest / shortest / count contiguous subarray or substring such that …" → sliding window.
- A fixed window size k is given ("max average of any k consecutive days") → fixed window.
- Palindromes, reversing, comparing from both ends → converging pointers.
- Linked list middle, cycle, k-th from end → fast/slow pointers (Linked Lists).
- "Max/min of every window" → sliding window plus a monotonic deque (Stacks, Queues & Monotonic Stacks).
Core concepts
Converging pointers and the elimination argument
With nums sorted ascending and l = 0, r = n − 1:
- If
nums[l] + nums[r] < target, thennums[l]plus any element at or left of r is too small —nums[l]can never be in an answer, sol++is safe. - If the sum is too big,
nums[r]plus anything at or right of l is too big, sor--is safe.
Every step discards one candidate permanently, so at most n steps. The same argument proves Container With Most Water (LeetCode 11): the area is limited by the shorter line, and moving the taller line inward can only shrink the width without raising that limit, so you always move the shorter one.
Read/write pointers
One pointer reads every element; the other marks where the next kept element goes. The kept prefix preserves order.
// compactNonZero removes zero amounts in place, keeping order, and returns
// the shortened slice. (slices.DeleteFunc does the same in the standard library.)
func compactNonZero(a []int64) []int64 {
w := 0
for _, v := range a {
if v != 0 {
a[w] = v
w++
}
}
return a[:w]
}
Sliding windows
A window is the contiguous range [left, right]. Two shapes:
- Fixed size k: add
a[right], and once the window exceeds k, removea[right − k]. Typical for moving averages and "max sum of k consecutive". - Variable size: grow by moving
right; restore validity by movingleft. For longest valid window, record the answer after shrinking (the window is valid). For shortest valid window, record inside the shrink loop while it is still valid.
The template — longest substring with at most k distinct bytes (LeetCode 340, and Fruit Into Baskets 904 with k = 2):
// longestAtMostKDistinct returns the length of the longest substring of s
// containing at most k distinct bytes.
func longestAtMostKDistinct(s string, k int) int {
count := make(map[byte]int)
best, left := 0, 0
for right := 0; right < len(s); right++ {
count[s[right]]++ // 1. expand
for len(count) > k { // 2. shrink while invalid
c := s[left]
count[c]--
if count[c] == 0 {
delete(count, c)
}
left++
}
best = max(best, right-left+1) // 3. [left, right] is valid
}
return best
}
Why O(n): right moves n times, left moves at most n times in total across all iterations of the inner loop. Nested loops, linear time — be ready to explain that, because interviewers check.
"Exactly K" via "at most K"
Counting windows with exactly k distinct values is hard to do directly: the valid set is not contiguous in left. But exactly(k) = atMost(k) − atMost(k − 1), and "at most" windows are monotone. For each right, every start in [left, right] is valid, so add right − left + 1.
// subarraysWithKDistinct counts subarrays with exactly k distinct values (LeetCode 992).
func subarraysWithKDistinct(nums []int, k int) int {
return atMostK(nums, k) - atMostK(nums, k-1)
}
func atMostK(nums []int, k int) int {
count := make(map[int]int)
total, left := 0, 0
for right, v := range nums {
count[v]++
for len(count) > k {
count[nums[left]]--
if count[nums[left]] == 0 {
delete(count, nums[left])
}
left++
}
total += right - left + 1 // subarrays ending at right
}
return total
}
When the window breaks
The window rule "shrink while invalid" assumes that removing elements moves the state monotonically toward valid. With negative numbers, removing an element can increase a sum, so "subarray sum = k" and "shortest subarray with sum ≥ k" (with negatives) need prefix sums with a hash map (Arrays & Hashing) or prefix sums with a monotonic deque (LeetCode 862).
Time-based windows: velocity checks
Fraud rules like "more than 5 card transactions in 60 seconds" are sliding windows over time instead of indices: keep timestamps per key, evict those older than now − window, compare the count.
// VelocityChecker flags a card that exceeds limit transactions within window.
// Not safe for concurrent use; timestamps per card must be non-decreasing.
type VelocityChecker struct {
window time.Duration
limit int
events map[string][]time.Time // card -> timestamps inside the window, ascending
}
func NewVelocityChecker(window time.Duration, limit int) *VelocityChecker {
return &VelocityChecker{window: window, limit: limit, events: make(map[string][]time.Time)}
}
// Allow records a transaction at t and reports whether the card is still within limit.
func (v *VelocityChecker) Allow(card string, t time.Time) bool {
ts := v.events[card]
cutoff := t.Add(-v.window)
i := 0
for i < len(ts) && !ts[i].After(cutoff) {
i++ // evict events at or before the cutoff: the left pointer
}
ts = append(ts[i:], t)
v.events[card] = ts
return len(ts) <= v.limit
}
In production this state lives outside the process so every replica sees it — typically a Redis sorted set per card (ZADD, ZREMRANGEBYSCORE, ZCARD in one script) or a stream processor with keyed windows. See Rate Limiting, Fraud & Risk Systems and Batch & Stream Processing for tumbling vs sliding vs session windows.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Converging pointers | O(n), O(1) space | Needs sorted input (sorting costs O(n log n) and loses original indexes) | Pair/triplet sums, palindromes, already-sorted data |
| Hash map lookup | Unsorted input, keeps indexes | O(n) memory | Two Sum on unsorted data, need original positions |
| Sliding window | O(n), small state | Requires a monotone validity condition | Contiguous ranges with non-negative contributions or distinct-count constraints |
| Prefix sum + map | Handles negatives | O(n) memory, counts rather than finds shortest | Exact-sum subarray counting |
| Window + monotonic deque | Window max/min in O(n) | More subtle code | Sliding window maximum, shortest subarray with negatives |
| Brute force | Trivial | O(n²) or O(n³) | Tiny n, or as a test oracle |
In practice
Problem 1 — Two Sum II, sorted input (LeetCode 167)
Problem. The slice is sorted ascending; find two positions whose values add up to the target using O(1) extra space.
Approach. Converging pointers with the elimination argument above.
func twoSumSorted(nums []int, target int) (int, int, bool) {
l, r := 0, len(nums)-1
for l < r {
switch sum := nums[l] + nums[r]; {
case sum == target:
return l, r, true
case sum < target:
l++ // nums[l] is too small even with the largest partner
default:
r-- // nums[r] is too large even with the smallest partner
}
}
return 0, 0, false
}
Complexity. O(n) time, O(1) space.
Problem 2 — 3Sum (LeetCode 15)
Problem. Return all unique triplets that sum to zero.
Approach. Sort, fix an anchor s[i], then run Two Sum II on the suffix for −s[i]. Deduplicate by skipping equal anchors and, after recording a triplet, skipping equal neighbours on both pointers. Early exit when the anchor is positive.
func threeSum(nums []int) [][3]int {
s := slices.Clone(nums)
slices.Sort(s)
var out [][3]int
for i := 0; i+2 < len(s); i++ {
if s[i] > 0 {
break // smallest element is positive: no zero sum possible
}
if i > 0 && s[i] == s[i-1] {
continue // duplicate anchor
}
l, r := i+1, len(s)-1
for l < r {
switch sum := s[i] + s[l] + s[r]; {
case sum < 0:
l++
case sum > 0:
r--
default:
out = append(out, [3]int{s[i], s[l], s[r]})
for l < r && s[l] == s[l+1] {
l++
}
for l < r && s[r] == s[r-1] {
r--
}
l++
r--
}
}
}
return out
}
Complexity. O(n²) time (O(n log n) sort is dominated), O(1) extra besides the clone and output. Follow-up: k-Sum generalizes by recursion down to two-pointer 2Sum, O(n^(k−1)).
Problem 3 — Longest Substring Without Repeating Characters (LeetCode 3)
Problem. Find the length of the longest substring with all distinct characters.
Approach. Variable window. Instead of shrinking one step at a time, remember the last position of each byte and jump left past the previous occurrence. max keeps left from moving backwards when the previous occurrence is already outside the window.
func lengthOfLongestSubstring(s string) int {
var last [256]int // index+1 of the last occurrence of each byte; 0 = never seen
best, left := 0, 0
for right := 0; right < len(s); right++ {
c := s[right]
left = max(left, last[c])
last[c] = right + 1
best = max(best, right-left+1)
}
return best
}
Complexity. O(n) time, O(1) space (256 counters). This treats the string as bytes; for Unicode text, iterate runes and use map[rune]int.
Problem 4 — Minimum Window Substring (LeetCode 76)
Problem. Find the shortest substring of s that contains every character of t (with multiplicity).
Approach. "Shortest" variant: expand until valid, then shrink while still valid, recording the best inside the shrink loop. need[c] holds how many more of c the window needs (negative = surplus); missing counts outstanding characters, so validity is an O(1) check.
func minWindow(s, t string) string {
if len(t) == 0 || len(t) > len(s) {
return ""
}
var need [256]int
for i := 0; i < len(t); i++ {
need[t[i]]++
}
missing := len(t)
bestL, bestLen := 0, len(s)+1
left := 0
for right := 0; right < len(s); right++ {
if need[s[right]] > 0 {
missing--
}
need[s[right]]--
for missing == 0 { // valid: record, then try to shrink
if right-left+1 < bestLen {
bestL, bestLen = left, right-left+1
}
need[s[left]]++
if need[s[left]] > 0 {
missing++ // we just dropped a required character
}
left++
}
}
if bestLen > len(s) {
return ""
}
return s[bestL : bestL+bestLen]
}
Complexity. O(|s| + |t|) time, O(1) space.
Practice list
- Easy: Valid Palindrome (125), Move Zeroes (283), Remove Duplicates from Sorted Array (26), Best Time to Buy and Sell Stock (121)
- Medium: Two Sum II (167), 3Sum (15), Container With Most Water (11), Longest Substring Without Repeating Characters (3), Longest Repeating Character Replacement (424), Permutation in String (567), Minimum Size Subarray Sum (209), Fruit Into Baskets (904)
- Hard: Minimum Window Substring (76), Trapping Rain Water (42), Sliding Window Maximum (239), Subarrays with K Different Integers (992)
Common pitfalls
- Using a window on data with negative numbers. Symptom: passes the examples, fails hidden tests. Ask about the value range first.
- Recording the answer in the wrong place — inside the shrink loop for "longest" (records invalid windows) or outside for "shortest" (misses the minimum).
- Forgetting to delete zero counts when using
len(map)as "distinct count" — the map keeps keys with count 0 and the window looks invalid forever. - Sorting when original indexes are required (Two Sum on unsorted input asks for indexes; sorting destroys them unless you sort index pairs).
- Duplicate results in 3Sum from not skipping equal anchors/neighbours, or skipping in the wrong place and losing valid triplets like
[-1, -1, 2]. - Bytes vs runes:
s[i]is a byte; a window over UTF-8 text by bytes splits multi-byte characters. - Unbounded per-key state in time windows (the velocity map grows with every card ever seen). In production, expire idle keys or keep the state in a store with TTLs.
Interview angle
- Say the template out loud: "expand right, shrink left while invalid, record when valid" — then justify why the left pointer never needs to move back (monotonicity). That justification is what separates pattern-matching from understanding.
- Explain the O(n) bound of the nested loop (amortized: each pointer moves at most n times).
- Expected follow-ups: "What if numbers can be negative?", "What if the input is a stream?" (bounded state per window; the window is the stream processor's state), "What if there are millions of keys?" (eviction, external state).
- Architect twist: tie windows to real systems — sliding-log vs sliding-counter rate limiters, fraud velocity rules, moving averages for anomaly detection on payment volume.
- Red flags: O(n²) "check every substring" without moving on, or a window solution with no explanation of correctness.
Self-check
1. In Two Sum II, why is it safe to discard nums[l] when the sum is too small?
The array is sorted, so nums[r] is the largest value still available. If even nums[l] + nums[r] is below the target, nums[l] plus any remaining element is below the target too. nums[l] cannot be part of any answer, so moving l loses nothing.
2. The window template has a loop inside a loop. Why is it still O(n)?
The inner loop only advances left, and left never moves backwards and never passes right. Across the entire run left moves at most n times and right moves exactly n times, so total work is O(n) — an amortized argument, not a per-iteration one.
3. Where do you record the answer for "longest valid window" versus "shortest valid window"?
Longest: after the shrink loop, when the window has just become valid again and is as large as possible for this right. Shortest: inside the shrink loop, before each shrink step, while the window is still valid — each shrink step tries a smaller valid window.
4. How do you count subarrays with exactly k distinct values, and why not directly?
Use atMost(k) − atMost(k − 1). For a fixed right end, the starts that give at most k distinct values form a contiguous range ending at right, which a window tracks easily. The starts giving exactly k form a range in the middle whose both ends move, which is awkward to maintain directly.
5. Why does a sliding window fail for "shortest subarray with sum ≥ k" when values can be negative, and what do you use?
Removing a negative value from the left increases the sum, so "shrink while valid" can skip over better windows; the validity is not monotone in left. Use prefix sums with a monotonic deque of increasing prefix values (LeetCode 862): O(n).
6. Scenario: the fraud team wants "block a card after 5 transactions within 60 seconds" across 20 API replicas. How do you implement it?
The algorithm is a time-based sliding window per card, but the state must be shared: a Redis sorted set per card scored by timestamp, updated atomically in a Lua script (remove entries older than now − 60 s, add the new one, count), with a TTL on the key. Consider idempotency (retries must not double-count — use the transaction ID as the member), clock source (use server time), and fail-open vs fail-closed if Redis is unavailable.
Exercise
Implement MaxDailyVolume(amounts []int64, k int) (start int, total int64) returning the k-day period with the largest total payment volume (fixed window), and ShortestPeriodOver(amounts []int64, threshold int64) int returning the shortest number of consecutive days whose volume reaches the threshold (variable window; amounts are non-negative).
Then extend VelocityChecker with an idle-key cleanup (Sweep(now time.Time)) and a benchmark with 1M cards. Done when: table-driven tests cover k > n, all-zero days and a threshold that is never reached; both functions are O(n); and you can explain in two sentences what changes if refunds (negative amounts) are allowed.
Further reading
- Aziz, Lee, Prakash, Elements of Programming Interviews — arrays and strings chapters
- Tech Interview Handbook (Yangshun Tay) — array and string cheat sheets, techinterviewhandbook.org
- NeetCode 150 — "Two Pointers" and "Sliding Window" sections (neetcode.io)
- Redis documentation — sorted sets (
ZADD,ZREMRANGEBYSCORE) for sliding-window counters
Related
- Arrays & Hashing — prefix sums when windows fail.
- Stacks, Queues & Monotonic Stacks — deques for window max/min.
- Linked Lists — fast/slow pointers.
- Rate Limiting — sliding log and sliding counter algorithms.
- Fraud & Risk Systems — velocity rules in production.
- Batch & Stream Processing — windowing in stream processors.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).