Part 16 / Topic 2 of 12
Hashing: the first tool to reach for
Hashing means computing a number (a hash) from a value so a HashMap/HashSet can jump straight to the right bucket instead of scanning. In interview terms: almost every "have I seen this?", "what pairs with this?" or "count how many of each" problem starts life as an O(n²) brute force and ends as an O(n) solution the moment a map replaces the inner loop.
Think of a cloakroom with numbered pigeonholes versus one with a single pile of coats: numbered holes mean you go straight to coat #42; a pile means checking coats one by one until you find it.
// Brute force: scan the rest of the array for a complement. O(n^2).
static int[] twoSumBruteForce(int[] prices, int target) {
for (int i = 0; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
if (prices[i] + prices[j] == target) return new int[]{i, j};
}
}
return null;
}
// Hashing: remember what you've seen, so the complement check is O(1). O(n) overall.
static int[] twoSumHashing(int[] prices, int target) {
Map<Integer, Integer> seenAt = new HashMap<>(); // price -> index
for (int i = 0; i < prices.length; i++) {
int complement = target - prices[i];
if (seenAt.containsKey(complement)) return new int[]{seenAt.get(complement), i};
seenAt.put(prices[i], i);
}
return null;
}
$ javac HashingDemo.java
$ java HashingDemo
-- two-sum: find two cart items that add up to a coupon target --
brute force O(n^2): [0, 3]
hashing O(n): [0, 3]
-- group anagram SKU codes --
key ACT -> [CAT, ACT, TAC]
key DGO -> [DOG, GOD]
-- first non-repeating character --
SWIGGYORDER -> S
-- duplicate UPI transaction IDs (should never happen, but did) --
duplicates: [TXN1001, TXN1002]
The anagram grouper and the duplicate-transaction finder are the same move in different clothes: compute one key per item (sorted letters; the item itself), and let the map do the "have I seen this key?" work in O(1) instead of comparing every item to every other item.
🔍 Going deeper:
HashMap/HashSetlookups are O(1) only with a good hash function and a reasonable load factor — this is a practical guarantee the JDK engineers tuned for, not a mathematical one for adversarial input.TreeMap/TreeSettrade that O(1) for guaranteed O(log n) and sorted iteration order (the heaps and trees sections build the underlying idea by hand).
Full program: examples/hashing/HashingDemo.java.
Done here? The practice set for Part 16 — including the solutions — is on the part page.