Practice: hash tables
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Putting hash table theory into practice solidifies your understanding. You will implement custom data structures from scratch and solve real-world pattern matching challenges.
Designing a custom HashSet without libraries
A HashSet is a hash table that keeps keys only. The class below builds one with chains and supports add and contains.
- Create a Node class holding a key and next pointer.
- Allocate a fixed array of Node references.
- Hash incoming keys to find target bucket indices.
- Traverse chains for membership checks and insertions.
Example 1 · Custom HashSet Implementation from Scratch
public class CustomHashSetDemo { static class Node { int key; Node next; Node(int k, Node n) { key = k; next = n; } }
private Node[] buckets = new Node[10];
public void add(int key) { int idx = Math.abs(key % buckets.length); for (Node c = buckets[idx]; c != null; c = c.next) { if (c.key == key) return; } buckets[idx] = new Node(key, buckets[idx]); }
public boolean contains(int key) { int idx = Math.abs(key % buckets.length); for (Node c = buckets[idx]; c != null; c = c.next) { if (c.key == key) return true; } return false; }
public static void main(String[] args) { CustomHashSetDemo set = new CustomHashSetDemo(); set.add(1); set.add(2); set.add(1); // Duplicate ignored System.out.println("Contains 1: " + set.contains(1)); System.out.println("Contains 3: " + set.contains(3)); }}Contains 1: true Contains 3: false
What this code does
- add checks for existing key before prepending a new node.
- Duplicate entry 1 is rejected without error.
- contains traverses bucket chain and reports accurate membership.
A HashSet stores unique keys without associated values.
It can be implemented using separate chaining with an array of linked list nodes. add(key) checks if the key already exists before appending.
contains(key) scans the bucket chain and returns true if found. remove(key) unlinks the node from the bucket list.
- Unique elements: duplicate insertions are ignored silently.
- Chained storage: each bucket holds a singly linked list of keys.
- Core operations:
add,contains, andremoveall execute in average O(1) time.
Isomorphic strings and word pattern matching
Two strings are isomorphic when each letter maps to exactly one letter in the other string, and the reverse. The method below checks this with two arrays of last-seen positions.
Example 2 · Isomorphic Strings Verification
public class IsomorphicStringsDemo { public static boolean isIsomorphic(String s, String t) { if (s.length() != t.length()) return false; int[] mapS = new int[256]; int[] mapT = new int[256];
for (int i = 0; i < s.length(); i++) { char c1 = s.charAt(i); char c2 = t.charAt(i); if (mapS[c1] != mapT[c2]) return false; mapS[c1] = i + 1; mapT[c2] = i + 1; } return true; }
public static void main(String[] args) { System.out.println("paper / title: " + isIsomorphic("paper", "title")); System.out.println("foo / bar: " + isIsomorphic("foo", "bar")); }}paper / title: true foo / bar: false
What this code does
- 'paper' and 'title' share identical positional patterns.
- 'foo' fails because 'o' maps to both 'a' and 'r'.
- Tracking last seen positions confirms bidirectional bijection in O(n) time.
Two strings are isomorphic if characters in s map to characters in t uniquely. This requires a strict one-to-one bijection between characters. A single character in s cannot map to two different characters in t.
Two different characters in s cannot map to the same character in t. We maintain two hash maps or integer arrays to enforce bidirectional consistency. For strings 'paper' and 'title': 'p' maps to 't', 'a' to 'i', 'e' to 'l' and 'r' to 'e'. Every character maps uniquely in both directions, so they are isomorphic. For strings 'foo' and 'bar': 'o' attempts to map to both 'a' and 'r'. This violates the bijection rule, so they are not isomorphic.
- Bijection requirement: one-to-one mapping in both directions.
- Dual mapping: track
s -> tandt -> ssimultaneously. - Conflict detection: mismatch between previous mappings immediately disproves isomorphism.
Find the bug
Find the isomorphic bug
Tap the line that gives a wrong answer.
The check must also reject "ab" and "cc".
Round 1 of 2Content-based duplicate detection and stress testing
Words with the same letters, or files with the same content, can be grouped by one shared key. The programs below group words that are anagrams of each other.
Example 3 · Brute force: compare every pair of words (O(n² · k log k) time, O(n) space)
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class GroupAnagramsBrute { static boolean sameLetters(String a, String b) { char[] x = a.toCharArray(); char[] y = b.toCharArray(); Arrays.sort(x); Arrays.sort(y); return Arrays.equals(x, y); }
public static List<List<String>> group(String[] words) { List<List<String>> groups = new ArrayList<>(); boolean[] used = new boolean[words.length]; for (int i = 0; i < words.length; i++) { if (used[i]) continue; List<String> g = new ArrayList<>(); for (int j = i; j < words.length; j++) { if (!used[j] && sameLetters(words[i], words[j])) { g.add(words[j]); used[j] = true; } } groups.add(g); } return groups; }
public static void main(String[] args) { String[] words = {"listen", "google", "silent", "cat", "gogole", "enlist", "act"}; System.out.println(group(words)); }}[[listen, silent, enlist], [google, gogole], [cat, act]]
What this code does
- Each word is compared with every later word by sorting both and checking equality, so n words need about n × n sorts of length k.
- It works with no map at all, but the work grows with the square of the number of words.
- The groups come out as listen, silent, enlist; google, gogole; cat, act.
Example 4 · Optimal: one pass with a sorted-letters key (O(n · k log k) time, O(n) space)
import java.util.*;
public class GroupAnagramsDemo { public static List<List<String>> group(String[] strs) { Map<String, List<String>> map = new LinkedHashMap<>(); for (String s : strs) { char[] chars = s.toCharArray(); Arrays.sort(chars); String key = new String(chars); map.computeIfAbsent(key, k -> new ArrayList<>()).add(s); } return new ArrayList<>(map.values()); }
public static void main(String[] args) { String[] words = {"listen", "google", "silent", "cat", "gogole", "enlist", "act"}; System.out.println(group(words)); }}[[listen, silent, enlist], [google, gogole], [cat, act]]
What this code does
- Sorting the letters of a word gives a key that is the same for all its anagrams, for example "eilnst".
- Each word is sorted once and then dropped into its group with one hash lookup, so no pair of words is ever compared.
- That removes the factor n: the total work is n sorts of length k.
Detecting duplicate files groups files by cryptographic content hashes rather than filenames. A hash map maps each content hash to a list of matching file paths. Stress testing custom hash maps inserts thousands of keys to verify resizing stability. All inserted keys must remain retrievable after multiple capacity expansions.
- Content hashing: grouping identical files by hash digest in linear time.
- Stress testing: inserting thousands of keys to verify rehashing under heavy load.
- Integrity check: ensuring zero keys are lost after resizing passes.
Finish up
Mark complete & continue
Next: Why sorting matters