Hashing in the real world
26 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Beyond in-memory hash maps, hashing powers critical software infrastructure. It enables lightning-fast deduplication, file verification, and distributed load balancing.
Removing duplicates and frequency analysis
Hash tables remove duplicates and count items in a single pass. The first program checks every earlier item the slow way; the next two get faster by sorting and then by using a HashSet.
- Initialize an empty HashSet to hold seen items.
- Iterate through input elements one by one.
- Check whether the element is already present in the set.
- If absent, process the item and add it to the set.
Example 1 · Brute force: nested scan for every item (O(n²) time, O(n) space)
import java.util.ArrayList;import java.util.List;
public class DedupBruteForce { public static List<String> removeDuplicates(String[] items) { List<String> result = new ArrayList<>(); for (String item : items) { boolean seenBefore = false; for (String kept : result) { if (kept.equals(item)) { seenBefore = true; break; } } if (!seenBefore) { result.add(item); } } return result; }
public static void main(String[] args) { String[] logs = {"warn", "error", "info", "warn", "error"}; System.out.println(removeDuplicates(logs)); }}[warn, error, info]
What this code does
- For every item, the inner loop scans the whole result list, so n items need up to n × n comparisons.
- Nothing but the result list is used, which is simple but slow on big inputs.
- The first appearance order is kept: warn, error, info.
Example 2 · Better: sort first, then compare neighbours (O(n log n) time, O(n) space)
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class DedupSorted { public static List<String> removeDuplicates(String[] items) { String[] sorted = items.clone(); Arrays.sort(sorted); List<String> result = new ArrayList<>(); for (int i = 0; i < sorted.length; i++) { if (i == 0 || !sorted[i].equals(sorted[i - 1])) { result.add(sorted[i]); } } return result; }
public static void main(String[] args) { String[] logs = {"warn", "error", "info", "warn", "error"}; System.out.println(removeDuplicates(logs)); }}[error, info, warn]
What this code does
- Sorting puts equal items side by side, so one pass comparing each item with the one before it is enough.
- Sorting costs O(n log n), which beats n × n because the array is halved again and again instead of rescanned.
- The original order is lost: the result comes out sorted (error, info, warn).
Example 3 · Optimal: one pass with a HashSet (O(n) average time, O(n) space)
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;
public class DeduplicationDemo { public static List<String> removeDuplicates(String[] items) { Set<String> seen = new HashSet<>(); List<String> result = new ArrayList<>(); for (String item : items) { if (seen.add(item)) { result.add(item); } } return result; }
public static void main(String[] args) { String[] logs = {"warn", "error", "info", "warn", "error"}; System.out.println(removeDuplicates(logs)); }}[warn, error, info]
What this code does
seen.add(item)returns false when the item is already in the set, so the check and the insert are one step.- A hash lookup takes O(1) time on average instead of scanning a list, so the whole pass is O(n). The price is O(n) extra memory for the set.
- The first appearance order is kept: warn, error, info.
Example 4 · Counting repeated log words with a HashMap (O(n) average time)
import java.util.HashMap;import java.util.Map;
public class WordFrequencyDemo { public static void main(String[] args) { String[] words = {"timeout", "login", "timeout", "payment", "timeout"}; Map<String, Integer> counts = new HashMap<>();
for (String w : words) { counts.put(w, counts.getOrDefault(w, 0) + 1); }
System.out.println("timeout count: " + counts.get("timeout")); System.out.println("unique words: " + counts.size()); }}timeout count: 3 unique words: 3
What this code does
getOrDefault(w, 0) + 1reads the current count, or 0 for a new word, and stores it back.- Each word needs one hash lookup, so counting n words takes O(n) time on average.
timeoutappears three times and there are three different words.
A HashSet filters out duplicate items during a single pass over an input stream. A HashMap counts frequencies of words, user sessions, or error codes. Compared to quadratic nested loops, hash-based deduplication is orders of magnitude faster.
- Deduplication: HashSet guarantees uniqueness with average O(1) membership checks.
- Frequency counting: HashMap maps elements to occurrence counters in O(n) total time.
- Streaming efficiency: processes unbounded incoming streams without sorting.
Order of execution
Run the HashSet loop
Tap what happens for each item, in order.
Checksums and file integrity verification
A cryptographic hash turns any data into a fixed-size digest. Change one character of the input and the digest changes completely, as the program below shows.
import java.security.MessageDigest;import java.util.HexFormat;
public class Checksum { public static void main(String[] args) throws Exception { MessageDigest sha = MessageDigest.getInstance("SHA-256"); for (String data : new String[] {"marks: 91", "marks: 97"}) { byte[] digest = sha.digest(data.getBytes("UTF-8")); // always 32 bytes String hex = HexFormat.of().formatHex(digest); System.out.println(data + " -> " + hex.substring(0, 16) + "..."); } }}marks: 91 -> 0a6302a97e455032... marks: 97 -> 06a084ca3f3d9dee...
A cryptographic hash function like SHA-256 produces a fixed-length digest from arbitrary data. Any change to even a single bit in the input produces a completely different digest. This avalanche effect makes hash digests ideal for detecting data corruption or tampering. Software downloads provide checksum hashes so users can verify file integrity.
- Digest: a fixed-size byte string representing arbitrary input data.
- Avalanche effect: minor input modifications cause drastic output changes.
- Integrity check: comparing computed checksums with published hashes verifies files.
Hashing is not encryption and consistent hashing
Hashing cannot be reversed, so it is not encryption. Consistent hashing places servers and keys on a ring so that adding a server moves only a few keys. The example builds a tiny ring.
Example 5 · A Minimal Consistent Hash Ring Demonstration
import java.util.NavigableMap;import java.util.TreeMap;
public class ConsistentHashRingDemo { private final NavigableMap<Integer, String> ring = new TreeMap<>();
public void addServer(String server) { int hash = Math.abs(server.hashCode() % 1000); ring.put(hash, server); }
public String getServer(String key) { if (ring.isEmpty()) return null; int hash = Math.abs(key.hashCode() % 1000); var entry = ring.ceilingEntry(hash); if (entry == null) { entry = ring.firstEntry(); // Wrap around ring } return entry.getValue(); }
public static void main(String[] args) { ConsistentHashRingDemo cluster = new ConsistentHashRingDemo(); cluster.addServer("Server-A"); cluster.addServer("Server-B"); cluster.addServer("Server-C");
System.out.println("user-101 -> " + cluster.getServer("user-101")); System.out.println("user-202 -> " + cluster.getServer("user-202")); }}user-101 -> Server-A user-202 -> Server-A
What this code does
- Servers and keys map to integer positions on a circular ring.
- ceilingEntry finds the next clockwise server handling the key.
- Wrap-around logic connects the ring tail to the ring head.
Hashing is a one-way mathematical function; digests cannot be decrypted. Encryption is a two-way function using a secret key to encode and decode data. In distributed systems, consistent hashing maps keys and servers onto a circular hash ring.
Suppose 3 servers handle cached keys using hash % 3. When server 4 joins, modulo becomes hash % 4. Over 70% of keys remap to new servers, causing a massive database cache stampede. Consistent hashing solves this by arranging servers and keys on a circular ring. Keys route clockwise to the next server. Adding server 4 only moves keys between server 3 and server 4. All other server caches remain untouched.
- One-way property: hashes cannot be reversed back to original plaintext.
- Encryption contrast: encryption requires a key and supports full decryption.
- Consistent hashing: minimizes key reassignment in distributed caches and databases.
Next step
Check your understanding
10 quick questions