Part 17 / 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).
fun twoSumBruteForce(prices: IntArray, target: Int): Pair<Int, Int>? {
for (i in prices.indices) {
for (j in i + 1 until prices.size) {
if (prices[i] + prices[j] == target) return i to j
}
}
return null
}
// Hashing: remember what you've seen, so the complement check is O(1). O(n) overall.
fun twoSumHashing(prices: IntArray, target: Int): Pair<Int, Int>? {
val seenAt = HashMap<Int, Int>() // price -> index
for (i in prices.indices) {
val complement = target - prices[i]
seenAt[complement]?.let { return it to i }
seenAt[prices[i]] = i
}
return null
}
$ kotlinc HashingDemo.kt -include-runtime -d hashing.jar
$ java -jar hashing.jar
-- two-sum: find two cart items that add up to a coupon target --
brute force O(n^2): (1, 3)
hashing O(n): (1, 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 uses groupBy { it.toCharArray().sorted().joinToString("") } — one key per item (the sorted letters), and the stdlib's own groupBy does the "have I seen this key?" work, which is the hashing move wearing a different outfit. The duplicate-transaction finder is the same idea by hand: a HashSet remembers what's already been seen, and seen.add(id) returning false is Kotlin's way of saying "this was already in the set" in one call instead of a separate contains + add.
🔍 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 (Kotlin'sHashMap/HashSeton the JVM genuinely arejava.util.HashMap/java.util.HashSetvia atypealias), not a mathematical one for adversarial input.TreeMap/TreeSetfromjava.utiltrade 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.kt.
Done here? The practice set for Part 17 — including the solutions — is on the part page.