Trade memory for speed
A hash map remembers what you have seen so you never search again. Spot the signal words — pair, count, duplicate, frequency, seen — and reach for it, then mention the extra O(n) space as the trade-off.
- TheoryHash functions, collisions and load factor.
- PatternsComplements, counting and prefix sums.
- DesignLRU cache with a map and a linked list.
Hash maps turn many O(n²) brute-force solutions into O(n). In coding rounds, the moment you hear “find a pair”, “count”, “duplicate” or “seen before”, think of a hash map. These questions cover the theory interviewers ask and the patterns that appear again and again.
1. How does a hash table work, and what is a collision?
A hash function turns a key into an array index. A collision happens when two keys map to the same index. Two common fixes: chaining (each slot holds a list, as in Java's HashMap) and open addressing (probe for the next free slot, as in Python's dict). With a good hash and a sensible load factor, operations stay O(1) on average.
2. Solve Two Sum in O(n).
For each number, check whether its complement has been seen; if not, remember the current number's index.
int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) return new int[] { j, i };
seen.put(nums[i], i);
}
return new int[0];
}3. Check whether two strings are anagrams.
Count characters in one string and subtract with the other; all counts must end at zero. For lowercase letters an int[26] is faster than a map.
boolean isAnagram(String a, String b) {
if (a.length() != b.length()) return false;
int[] count = new int[26];
for (int i = 0; i < a.length(); i++) {
count[a.charAt(i) - 'a']++;
count[b.charAt(i) - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
}4. Find the first non-repeating character in a string.
Two passes: count every character, then return the first one whose count is 1. A LinkedHashMap also works because it keeps insertion order.
char firstUnique(String s) {
Map<Character, Integer> freq = new LinkedHashMap<>();
for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);
for (var e : freq.entrySet()) if (e.getValue() == 1) return e.getKey();
return '_';
}5. Count subarrays whose sum equals k.
Keep a running prefix sum and a map of how often each prefix sum has occurred. If prefix - k was seen before, every occurrence marks a subarray ending here with sum k. This works with negative numbers, where the sliding window fails.
int subarraySum(int[] nums, int k) {
Map<Integer, Integer> seen = new HashMap<>(Map.of(0, 1));
int prefix = 0, count = 0;
for (int x : nums) {
prefix += x;
count += seen.getOrDefault(prefix - k, 0);
seen.merge(prefix, 1, Integer::sum);
}
return count;
}6. Group words that are anagrams of each other.
Use a canonical key — the sorted letters — so all anagrams share one map entry.
Map<String, List<String>> groups = new HashMap<>();
for (String w : words) {
char[] c = w.toCharArray();
Arrays.sort(c);
groups.computeIfAbsent(new String(c), k -> new ArrayList<>()).add(w);
}7. Design an LRU cache with O(1) get and put.
Combine a hash map (key → node, for O(1) lookup) with a doubly linked list (for O(1) move-to-front and removal of the least recently used item at the tail). In Java you can get the same behaviour from LinkedHashMap with access order, but interviewers often want to see the map + list design explained.
8. What makes a good hash function?
It is fast, deterministic, and spreads keys evenly so few collide. Small changes in the key should change the hash a lot. For security-sensitive uses (passwords, signatures) you need a cryptographic hash such as SHA-256 or a password hash such as bcrypt or Argon2 — which is a different job from a hash table index.
Remember
Key points
- O(1) average, O(n) worst
Heavy collisions degrade performance.
- Prefix sum + map
Handles subarray sums with negative numbers.
- Canonical keys
Sorted letters or counts group anagrams.
- Arrays beat maps for small alphabets
int[26] for lowercase letters.
Interview drill
Follow-up questions
What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.
-
1 How would you find the longest substring without repeating characters? Intermediate
Sliding window with a map from character to its last index; when you see a repeat inside the window, move the left edge past its previous position.
-
2 Why can a hash table become slow even with a good hash function? Intermediate
A high load factor or many equal keys crowd buckets. Resizing (rehashing) keeps chains short but costs O(n) at that moment.
-
3 What is consistent hashing? Advanced
A scheme that places servers and keys on a ring so that adding or removing a server moves only a small fraction of keys. Used by distributed caches and databases.
-
4 How do you detect a duplicate in an array of n+1 numbers from 1 to n without extra space? Advanced
Treat values as next pointers and use Floyd's cycle detection — the cycle entrance is the duplicate.
-
5 Is HashSet.contains() always O(1)? Basic
On average, yes. In the worst case it depends on the bucket: O(log n) for treeified buckets in Java 8+, O(n) for long chains.