DSA Guide
Arrays

Arrays

Two pointers, sliding windows, prefix sums and hash maps — the patterns behind most array problems

Arrays are where almost every algorithm interview starts, and for good reason: they force you to think about access patterns. An array gives you O(1) random access but O(n) insertion and deletion, and nearly every technique below is a way of exploiting the first to avoid paying the second.

The Four Patterns

Almost every array problem here is one of these.

1. Hash map — turn searching into looking up

When you find yourself writing a nested loop to find "the other half" of something, a hash map usually collapses it to one pass. The cost is O(n) memory.

2. Two pointers — let a sorted (or symmetric) structure guide you

Two indices moving under a rule that provably discards possibilities. The hard part is always the proof that what you skip could not have been the answer.

3. Prefix sums — precompute so range queries become subtraction

Build cumulative totals once, and any range question becomes O(1) arithmetic.

4. Single-pass running state — carry the answer as you go

Keep one or two variables that summarise everything seen so far. Often a dynamic-programming table collapsed down to scalars.

How to Recognise Which One

The problem says…Reach for
"find a pair / has this appeared before"Hash map or set
"the array is sorted"Two pointers or binary search
"sum of a subarray / range"Prefix sums
"subarray of size k"Fixed sliding window
"longest / shortest subarray such that…"Variable sliding window
"in place, O(1) extra space"Read and write pointers
"k most frequent / largest"Counting, then bucket sort or a heap

All Problems

ProblemDifficultyPattern
Two SumEasyHash Map
Contains DuplicateEasyHash Set
Best Time to Buy and Sell StockEasyRunning Minimum
Running Sum of 1d ArrayEasyPrefix Sum
Find Pivot IndexEasyPrefix Sum
Maximum Average Subarray IEasySliding Window
Merge Sorted ArrayEasyTwo Pointers
Number of Good PairsEasyCounting
Minimum Index Sum of Two ListsEasyHash Map
Sort the PeopleEasyCustom Sort
Final Value of VariableEasySimulation
Container With Most WaterMediumTwo Pointers
Product of Array Except SelfMediumPrefix & Suffix
Group AnagramsMediumHash Map
Top K Frequent ElementsMediumBucket Sort
H-IndexMediumSorting
Remove Duplicates from Sorted Array IIMediumTwo Pointers
Trapping Rain WaterHardTwo Pointers

Where to start

If you are new to these, work through Two Sum, then Best Time to Buy and Sell Stock, then Container With Most Water. Those three cover hash maps, running state and two pointers — and everything else builds on them.

On this page