The pattern: arrays and hashing
Trade a little memory for speed by remembering what you've seen in a set or map, turning O(n²) searches into O(n).
Many array problems ask, in some form, "have I seen this before?" or "how many times?" The slow way checks every pair of elements: O(n²). The fast way walks the array once and remembers what it saw in a HashSet or HashMap, where a lookup takes O(1) on average.
01The idea in one picture
Walk left to right. For each value, first ask the memory, then update it.
memory = empty set or map
for each value x:
if memory already knows x → we found what we need
put x into memory02When to use it
- Duplicates: "does any value appear twice?"
- Counting: "how often does each value appear?", "most frequent"
- Matching: "two values that add up to a target", "common elements"
- Grouping: "group words that are anagrams"
- Arrays rewritten in place: move, remove or compact values with a write pointer.
03The Java tools you'll use
| Need | Use |
|---|---|
| Have I seen x? | Set<Integer> seen = new HashSet<>() |
| How many times? | map.merge(x, 1, Integer::sum) |
| Group items under a key | map.computeIfAbsent(key, k -> new ArrayList<>()).add(x) |
| Values are small (a–z, 0–9) | a plain int[26] array: even faster |
import java.util.*;
public class CountDemo {
public static void main(String[] args) {
int[] nums = {3, 1, 3, 2, 1, 3};
Map<Integer, Integer> count = new TreeMap<>();
for (int x : nums) count.merge(x, 1, Integer::sum);
System.out.println(count);
}
}{1=2, 2=1, 3=3}04The cost
Memory goes up to O(n). That's almost always fine in interviews; say it out loud anyway: "I'm trading O(n) extra space for O(n) time."
05Problems in this chapter
Contains Duplicate, Single Number and Plus One are free to start with. Then: stock prices, in-place compaction (Move Zeroes, Remove Element, Remove Duplicates), counting (Intersection, Roman numerals, Reduce Array Size), strings (Longest Common Prefix, Group Anagrams), a matrix (Rotate Image) and intervals (Merge Intervals).