DSA & CS / 1. ARRAYS & TWO POINTERS
Arrays & Two Pointers
The most common pattern in interviews — O(n) from O(n²)
EXPLANATION
Arrays are contiguous memory blocks. Random access is O(1), but insertion/deletion in the middle is O(n) because elements must shift. Two Pointers is a pattern that uses two indices (left, right or slow, fast) moving through an array to avoid a nested loop — turning O(n²) into O(n). When to use Two Pointers: • Sorted array → pair sum, triplet sum, target difference • Palindrome check → left and right move inward • Remove duplicates in-place → slow/fast pointers • Merging two sorted arrays Sliding Window is a variant — a window [left, right] expands/contracts: • Fixed window → move both pointers together • Variable window → expand right until valid, shrink left until invalid Pattern recognition: "subarray", "substring", "contiguous", "window" → try sliding window first.
DIAGRAM
Two Pointers — pair sum in sorted array:
[1, 2, 3, 4, 6] target = 6
L R
1+6=7 > 6 → move R left
L R
1+4=5 < 6 → move L right
L R
2+4=6 ✓ found!
Sliding Window — max sum subarray of size k=3:
[2, 1, 5, 1, 3, 2]
[2+1+5]=8
[1+5+1]=7
[5+1+3]=9 ← max
[1+3+2]=6CODE