Lab 10 – Hashing
Part 1 – Hash tables from scratch¶
Task 1 – Two hash functions for strings¶
Write sumHash, which adds the character codes, and polyHash, which computes
with Horner’s rule, both modulo m. Compare them on
six anagrams with .
static int sumHash(String s, int m) { /* ToDo */ }
static int polyHash(String s, int m) { /* ToDo: h = (31 * h + s.charAt(i)) % m */ }Solution
static int sumHash(String s, int m) { // a bad hash: ignores the order
int h = 0;
for (int i = 0; i < s.length(); i++)
h += s.charAt(i);
return h % m;
}
static int polyHash(String s, int m) { // Horner: s0*31^(n-1) + ... + s(n-1)
int h = 0;
for (int i = 0; i < s.length(); i++)
h = (31 * h + s.charAt(i)) % m;
return h;
}String[] words = {"stop", "pots", "tops", "opts", "post", "spot"};
for (String w : words)
System.out.printf("%s: sum %3d poly %3d%n", w, sumHash(w, 101), polyHash(w, 101));Expected output:
stop: sum 50 poly 35
pots: sum 50 poly 46
tops: sum 50 poly 7
opts: sum 50 poly 1
post: sum 50 poly 16
spot: sum 50 poly 33The sum puts all six words in the same cell; the polynomial hash spreads them out because it depends on the position of each character.
Task 2 – Linear probing¶
Store integers in an Integer[] (null = empty) with . On a collision,
try the next cell, wrapping round at the end. insert returns the number of probes.
🚩
containsstops at the first empty cell: the key cannot be further away.
class LinearProbingSet {
Integer[] table;
LinearProbingSet(int m) { table = new Integer[m]; }
int insert(int k) { /* ToDo */ }
boolean contains(int k) { /* ToDo */ }
}Solution
class LinearProbingSet {
Integer[] table; // null = empty cell
LinearProbingSet(int m) { table = new Integer[m]; }
int h(int k) { return Math.floorMod(k, table.length); }
int insert(int k) { // returns the number of probes
int i = h(k), probes = 1;
while (table[i] != null) {
if (table[i] == k) return probes; // already there
i = (i + 1) % table.length; // try the next cell
probes++;
}
table[i] = k;
return probes;
}
boolean contains(int k) {
int i = h(k);
while (table[i] != null) { // stop at the first empty cell
if (table[i] == k) return true;
i = (i + 1) % table.length;
}
return false;
}
}The keys of the slides (Weiss), :
LinearProbingSet lp = new LinearProbingSet(10);
for (int k : new int[]{89, 18, 49, 58, 69})
System.out.println("insert " + k + ": " + lp.insert(k) + " probe(s)");
System.out.println(Arrays.toString(lp.table));
System.out.println("contains 58? " + lp.contains(58) + ", contains 28? " + lp.contains(28));Expected output:
insert 89: 1 probe(s)
insert 18: 1 probe(s)
insert 49: 2 probe(s)
insert 58: 4 probe(s)
insert 69: 4 probe(s)
[49, 58, 69, null, null, null, null, null, 18, 89]
contains 58? true, contains 28? falseTask 3 – Quadratic probing with (final exam)¶
Insert 15, 23, 11, 68, 57, 26, 43, 34, 20, 60 into a table of size 17 with , probing
🚩
h - i*ican be negative: useMath.floorMod(x, m)instead ofx % m.
Solution
class QuadraticSet {
Integer[] table;
QuadraticSet(int m) { table = new Integer[m]; }
int h(int k) { return (3 * k + 2) % table.length; } // the exam's function
void insert(int k) {
int m = table.length, base = h(k);
// probe base, base+1, base-1, base+4, base-4, base+9, ...
for (int i = 0; i < m; i++) {
int[] tries = (i == 0) ? new int[]{base}
: new int[]{base + i * i, base - i * i};
for (int t : tries) {
int idx = Math.floorMod(t, m);
if (table[idx] == null) {
table[idx] = k;
return;
}
}
}
System.out.println("no free cell found for " + k);
}
}QuadraticSet qs = new QuadraticSet(17);
for (int k : new int[]{15, 23, 11, 68, 57, 26, 43, 34, 20, 60})
qs.insert(k);
for (int i = 0; i < 17; i++)
if (qs.table[i] != null)
System.out.print(i + ":" + qs.table[i] + " ");
System.out.println();Expected output (the exam answer):
1:11 2:68 3:23 4:57 6:34 10:20 11:43 12:26 13:15 16:60 Task 4 – Separate chaining with rehashing¶
Each cell holds a java.util.LinkedList<Integer>. When the load factor
goes above 1, allocate a table twice as large and re-insert every key: its cell
changes, because m changed.
class ChainedSet {
private LinkedList<Integer>[] table;
private int n = 0;
// ToDo: constructor, contains, add (with rehash), size, capacity, loadFactor
}Solution
class ChainedSet {
private LinkedList<Integer>[] table;
private int n = 0;
@SuppressWarnings("unchecked")
ChainedSet(int m) {
table = new LinkedList[m];
for (int i = 0; i < m; i++) table[i] = new LinkedList<>();
}
private int h(int k) { return Math.floorMod(k, table.length); }
boolean contains(int k) { return table[h(k)].contains(k); }
void add(int k) {
if (contains(k)) return;
table[h(k)].addFirst(k);
n++;
if (loadFactor() > 1.0) rehash(); // keep the chains short
}
@SuppressWarnings("unchecked")
private void rehash() {
LinkedList<Integer>[] old = table;
table = new LinkedList[2 * old.length];
for (int i = 0; i < table.length; i++) table[i] = new LinkedList<>();
for (LinkedList<Integer> chain : old) // every key moves: m has changed
for (int k : chain)
table[h(k)].addFirst(k);
}
int size() { return n; }
int capacity() { return table.length; }
double loadFactor() { return (double) n / table.length; }
}ChainedSet cs = new ChainedSet(4);
for (int k = 1; k <= 20; k++) {
cs.add(k * 7);
if (k % 5 == 0)
System.out.printf("%2d keys: table size %2d, load factor %.2f%n",
cs.size(), cs.capacity(), cs.loadFactor());
}
System.out.println("contains 70? " + cs.contains(70) + ", contains 71? " + cs.contains(71));Expected output:
5 keys: table size 8, load factor 0.63
10 keys: table size 16, load factor 0.63
15 keys: table size 16, load factor 0.94
20 keys: table size 32, load factor 0.63
contains 70? true, contains 71? falsePart 2 – Use the JDK¶
Challenge 1 – Two sum on an unsorted array¶
Find indices i < j with a[i] + a[j] == t in one pass: for each a[j], ask a
HashMap<Integer, Integer> (value → index) whether t - a[j] was seen before.
Solution
static int[] twoSum(int[] a, int t) {
Map<Integer, Integer> pos = new HashMap<>(); // value -> index
for (int j = 0; j < a.length; j++) {
Integer i = pos.get(t - a[j]); // seen the partner before?
if (i != null)
return new int[]{i, j};
pos.put(a[j], j);
}
return null;
}System.out.println(Arrays.toString(twoSum(new int[]{11, 7, 2, 15}, 9)));
System.out.println(Arrays.toString(twoSum(new int[]{3, 8, 4, 1}, 100)));Expected output:
[1, 2]
nullChallenge 2 – Word frequencies¶
Count the words of a sentence with freq.merge(w, 1, Integer::sum), print the counts in
alphabetical order, and find the most frequent word.
Solution
String text = "to be or not to be that is the question to ask";
Map<String, Integer> freq = new HashMap<>();
for (String w : text.split(" "))
freq.merge(w, 1, Integer::sum); // 1 if new, otherwise +1
String best = null;
for (Map.Entry<String, Integer> e : freq.entrySet())
if (best == null || e.getValue() > freq.get(best))
best = e.getKey();
System.out.println(new TreeMap<>(freq)); // printed in sorted order
System.out.println("most frequent: " + best + " (" + freq.get(best) + ")");Expected output:
{ask=1, be=2, is=1, not=1, or=1, question=1, that=1, the=1, to=3}
most frequent: to (3)Challenge 3 – The first character that appears only once¶
Count every character, then scan the string again and return the first one with count 1
(null if there is none).
Solution
static Character firstUnique(String s) {
Map<Character, Integer> count = new HashMap<>();
for (char c : s.toCharArray())
count.merge(c, 1, Integer::sum);
for (char c : s.toCharArray()) // second pass, in order
if (count.get(c) == 1)
return c;
return null;
}System.out.println(firstUnique("swiss") + " " + firstUnique("aabb")
+ " " + firstUnique("datastructures"));Expected output:
w null dChallenge 4 – Group anagrams¶
Anagrams have the same sorted letters. Use them as the key of a
Map<String, List<String>>; computeIfAbsent(key, k -> new ArrayList<>()) creates the list
the first time a key is seen.
Solution
String[] ws = {"eat", "tea", "tan", "ate", "nat", "bat"};
Map<String, List<String>> groups = new TreeMap<>();
for (String w : ws) {
char[] c = w.toCharArray();
Arrays.sort(c);
String key = new String(c); // anagrams share this key
groups.computeIfAbsent(key, k -> new ArrayList<>()).add(w);
}
System.out.println(groups);Expected output:
{abt=[bat], aet=[eat, tea, ate], ant=[tan, nat]}Challenge 5 – The equals / hashCode trap¶
Put the point in a HashSet, then ask whether a new point is in it,
with three versions of the class: without equals and hashCode, with both, and as a
record.
The three classes
static class PointBad { // no equals, no hashCode
int x, y;
PointBad(int x, int y) { this.x = x; this.y = y; }
}
static class PointGood {
int x, y;
PointGood(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
return o instanceof PointGood p && x == p.x && y == p.y;
}
@Override public int hashCode() {
return 31 * x + y; // equal points -> equal hash codes
}
}
record PointRecord(int x, int y) {} // a record writes both for youSet<PointBad> s1 = new HashSet<>();
s1.add(new PointBad(1, 2));
Set<PointGood> s2 = new HashSet<>();
s2.add(new PointGood(1, 2));
Set<PointRecord> s3 = new HashSet<>();
s3.add(new PointRecord(1, 2));
System.out.println("PointBad: " + s1.contains(new PointBad(1, 2)));
System.out.println("PointGood: " + s2.contains(new PointGood(1, 2)));
System.out.println("PointRecord: " + s3.contains(new PointRecord(1, 2)));Expected output:
PointBad: false
PointGood: true
PointRecord: trueWithout hashCode, two equal points get different hash codes, so the set looks in the
wrong chain and answers false. The rule: equal objects must have equal hash codes,
so override equals and hashCode together (a record does it for you).