Arrays & Hashing · Lesson
Arrays and hashing, explained: the ideas, the templates and every pattern
Learn arrays, strings and hash maps: two pointers, sliding window, prefix sums, Kadane and more, with templates in Java, Python, C++ and JavaScript.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
What an array gives you
An array is one block of memory with the items side by side. Because every item has the same size, the computer finds item i with one multiplication: reading or writing any index is O(1). Strings are arrays of characters, so everything here works on them too.
The price is the middle: inserting or deleting at position i shifts every item after it, which is O(n). Appending at the end of a dynamic array (ArrayList, Python list, vector) is O(1) on average.
What a hash map gives you
A hash map (and its cousin, the hash set) answers "have I seen this?" and "how many times?" in O(1) on average. It turns a value into an index with a hash function, so it does not care about order.
Most array problems that look O(n²) become O(n) with one of two moves: remember what you have seen in a hash map, or use the order of the array with pointers or a window so each element is touched a constant number of times.
How to pick the pattern
- Pairs that add up to something: a hash map of complements, or two pointers if the array is sorted.
- A contiguous subarray or substring: a sliding window when the condition only gets worse as the window grows; prefix sums when you need exact sums or counts.
- The best subarray ending here: Kadane.
- Do it in place, O(1) extra space: read/write pointers, sign marking, reversing.
- Group, count or match: a hash map keyed by a canonical form.
What it costs
| Operation | Time | Space |
|---|---|---|
| Read or write a[i] | O(1) | O(1) |
| Append at the end (dynamic array) | O(1) average | O(1) |
| Insert or delete in the middle | O(n) | O(1) |
| Search an unsorted array | O(n) | O(1) |
| Sort | O(n log n) | O(log n) to O(n) |
| Hash map get / put / contains | O(1) average | O(n) total |
Built into your language
int[] a = {5, 2, 8, 2};
Arrays.sort(a); // [2, 2, 5, 8]
List<Integer> list = new ArrayList<>(List.of(3, 1));
list.add(4); // append, O(1) average
Map<Integer, Integer> count = new HashMap<>();
for (int x : a) count.merge(x, 1, Integer::sum); // {2=2, 5=1, 8=1}
Set<String> seen = new HashSet<>();
seen.add("ab"); seen.contains("ab"); // true
StringBuilder sb = new StringBuilder(); // build strings in O(n)
sb.append('x').append(42); a = [5, 2, 8, 2]
a.sort() # [2, 2, 5, 8]
a.append(4) # O(1) average
from collections import Counter, defaultdict
count = Counter(a) # Counter({2: 2, 5: 1, 8: 1, 4: 1})
groups = defaultdict(list)
groups["key"].append(1)
seen = set(); seen.add("ab"); "ab" in seen # True
s = "".join(["x", "42"]) # build strings in O(n) vector<int> a = {5, 2, 8, 2};
sort(a.begin(), a.end()); // {2, 2, 5, 8}
a.push_back(4); // O(1) average
unordered_map<int, int> count;
for (int x : a) count[x]++; // {2:2, 5:1, 8:1, 4:1}
unordered_set<string> seen;
seen.insert("ab"); seen.count("ab"); // 1
string s; s += 'x'; s += to_string(42); // build strings in O(n) const a = [5, 2, 8, 2];
a.sort((x, y) => x - y); // [2, 2, 5, 8] (always pass a comparator for numbers)
a.push(4); // O(1) average
const count = new Map();
for (const x of a) count.set(x, (count.get(x) ?? 0) + 1);
const seen = new Set();
seen.add("ab"); seen.has("ab"); // true
const s = ["x", "42"].join(""); // build strings in O(n) Mistakes everyone makes
- Sorting numbers in JavaScript without a comparator:
[10, 9, 1].sort()gives[1, 10, 9]. - Building a string with
+=in a loop in Java: each step copies the string. Use a StringBuilder. - Modifying a list while iterating over it.
- Forgetting that a hash map with
int[](Java) or list (Python) keys hashes by identity or fails: convert to a string or tuple. - Integer overflow when summing or multiplying: use long (Java), long long (C++).
The 26 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 Two Sum: find pairs with a hash map For each number, the partner you need is
target - x. Keep every number you have passed in a hash map and ask whether the partner is already there: one pass, O(n). 4 variations · 4 problems - 2 Moore's voting: the majority in O(1) space Pair off different values and cancel them. Whatever survives is the only possible majority. One pass and two variables, no hash map. 2 variations · 2 problems
- 3 Kadane's algorithm: the best subarray ending here At each index, the best subarray ending here either extends the best one ending at the previous index or starts fresh. Track that and the best seen so far. 5 variations · 7 problems
- 4 The double reversal trick Reverse the whole thing, then reverse each part. Rotating an array by k or reversing the order of words becomes O(n) time and O(1) extra space. 2 variations · 2 problems
- 5 Two pointers Two indexes that only move forward (or toward each other), so the whole scan is O(n). Opposite ends for sorted pairs and palindromes; a read and a write pointer for in-place edits; one pointer per sequence for comparing. 6 variations · 37 problems
- 6 Right to left: suffix maximums, products and carries Some answers depend on everything to the right. Walk from the end and carry what you need: the largest value so far, a running product, or a carry digit. 4 variations · 12 problems
- 7 In-place transformations Reuse the input as your memory. Values in 1..n can mark "seen" by flipping the sign at an index; a matrix can store its own flags in its first row and column. 3 variations · 5 problems
- 8 Merge sort, and counting while you merge Merge sort splits, sorts both halves, then merges. During the merge you know which left values are bigger than a right value, which counts inversions and similar pairs in O(n log n). 2 variations · 4 problems
- 9 Dutch national flag: three-way partition Three regions grow at once: 0s on the left, 2s on the right, 1s in the middle, and an unknown part shrinking between them. One pass, in place. 1 variation · 1 problem
- 10 Prefix sums prefix[i] = sum of the first i values, so any subarray sum is a difference of two prefixes. With a hash map of earlier prefixes you can count subarrays with an exact sum, remainder or XOR in one pass. 5 variations · 17 problems
- 11 Sliding window of a fixed size A window of exactly k items slides one step at a time: add the item coming in, remove the item going out. Every window is updated in O(1) instead of recomputed. 3 variations · 11 problems
- 12 Sliding window of a variable size Grow the window on the right; when it breaks the rule, shrink it from the left until it is valid again. Both ends only move forward, so it is O(n). 4 variations · 15 problems
- 13 Sliding window with a hash map When the rule is about which values are inside the window (cover every letter of t, at most k distinct values), keep their counts in a hash map plus one number that says how many requirements are met. 3 variations · 8 problems
- 14 Hashing: count, group and map A hash map turns "search the whole array" into one lookup. Count frequencies, group items by a canonical key, or map one thing to another to check a one-to-one rule. 5 variations · 25 problems
- 15 Matrix traversal: spirals and diagonals Walk a grid in a non-obvious order. Spirals peel off layers using four shrinking boundaries; diagonals group cells by i + j (or i − j). 3 variations · 6 problems
- 16 The Josephus elimination recurrence n people in a circle, every k-th one leaves. Simulating is O(n·k). The survivor satisfies J(1) = 0 and J(n) = (J(n − 1) + k) mod n, which is O(n). 1 variation · 1 problem
- 17 Greedy: make the safe choice now Make the choice that looks best right now and never undo it. It works when you can argue that some best answer always starts with that choice; usually after sorting. 6 variations · 28 problems
- 18 Hash set lookups Put everything in a set, then ask O(1) questions. For runs of consecutive numbers, start counting only at numbers whose predecessor is missing, so the whole thing is O(n). 3 variations · 6 problems
- 19 Simulation: do exactly what the problem says No trick, just careful bookkeeping. Represent the state cleanly (direction vectors, an index into the input), handle every edge case the statement mentions, and test on the examples. 4 variations · 13 problems
- 20 The contribution technique Instead of looping over every substring, ask how many substrings each element contributes to. A character is unique in (i − prev) × (next − i) substrings. 2 variations · 2 problems
- 21 KMP: string matching in O(n + m) The prefix function lps[i] is the length of the longest proper prefix of the pattern that is also a suffix ending at i. On a mismatch, jump back to lps instead of restarting, so nothing is compared twice. 3 variations · 3 problems
- 22 Math and number theory A handful of facts solve a whole family of problems: the sieve for primes, GCD for reachability, base conversion for digits, and a counting formula instead of a loop. 5 variations · 13 problems
- 23 Generate a few candidates, keep the best When the answer must be one of a small set of shapes, build every candidate and compare them, instead of searching the whole space. 2 variations · 2 problems
- 24 Fenwick tree: prefix sums with updates A Fenwick tree keeps prefix sums that you can update in O(log n). Walk the values in order, and "how many smaller values came before me?" is a prefix query. 1 variation · 1 problem
- 25 String basics Compare character by character, split into parts, and remember the classic tricks: a rotation of s is a substring of s + s, and length-prefix encoding survives any character. 3 variations · 7 problems
- 26 Sort first, then compare neighbours After sorting, the closest pair is always next to each other. One sort and one pass, plus the wrap-around pair for circular values like times of day. 2 variations · 2 problems