Skip to lesson

HashMap and HashSet patterns

When data is unsorted and you need to answer "Have I seen x before?", "How many times did x appear?", or "Where did target - x appear?", HashSet and HashMap trade O(n) memory to drop inner-loop searches from O(n) down to O(1) expected time.

Frequency counting and Seen-before checks

Hashing is turning a key into a number that decides where it is stored, so it can be found again in O(1) time on average. HashMap and HashSet are built on it.

Two hashing idioms appear in almost every interview: a set for seen-before checks, and a map for counting.

Example 1 · Frequency counting and seen-before checks: First Unique Character & Contains Duplicate II

FrequencyAndSeenDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class FrequencyAndSeenDemo {    public static int firstUniqChar(String s) {        int[] freq = new int[26];        for (int i = 0; i < s.length(); i++) {            freq[s.charAt(i) - 'a']++;        }        for (int i = 0; i < s.length(); i++) {            if (freq[s.charAt(i) - 'a'] == 1) {                return i;            }        }        return -1;    }
    public static boolean containsNearbyDuplicate(int[] nums, int k) {        Map<Integer, Integer> lastIndex = new HashMap<>();        for (int i = 0; i < nums.length; i++) {            Integer prev = lastIndex.put(nums[i], i);            if (prev != null && i - prev <= k) {                return true;            }        }        return false;    }
    public static void main(String[] args) {        System.out.println("First unique in loveleetcode: " + firstUniqChar("loveleetcode"));        int[] nums = {1, 2, 3, 1};        System.out.println("Nearby duplicate (k=3): " + containsNearbyDuplicate(nums, 3));    }}
Output
First unique in loveleetcode: 2
Nearby duplicate (k=3): true

What this code does

  • firstUniqChar makes two linear passes: pass 1 builds the frequency table, and pass 2 finds the first index with count == 1.
  • In containsNearbyDuplicate, Map.put(key, val) returns the previous value associated with key (or null), letting us update and check in a single map operation.
  1. Seen-before checks (HashSet<T>): To detect duplicates (Contains Duplicate), find the first repeated element, or test membership in O(1) expected time, call set.add(x), which returns false if x is already in the set.
  2. Frequency counting (HashMap<T, Integer> or int[]): To count occurrences of each element (First Unique Character, Majority Element, Ransom Note), update the map with freq.put(x, freq.getOrDefault(x, 0) + 1) or freq.merge(x, 1, Integer::sum). When keys are lowercase ASCII letters 'a'..'z', an int[26] array is even faster.
  • set.add(x) both checks and inserts in a single hash lookup, returning false if x was already present.
  • freq.getOrDefault(x, 0) + 1 safely handles missing keys without NullPointerException.
  • In Java 17, HashSet and HashMap operations run in O(1) expected time (assuming a good hashCode function).

Two sum with a map

In unsorted Two Sum, given int[] nums and int target, we must return the indices of the two numbers that add up to target. Remember from the Two Pointers module why sorting + two pointers is awkward here: sorting scrambles the original indices!

  1. Create Map<Integer, Integer> seen = new HashMap<>().
  2. For i = 0 .. nums.length - 1, compute int need = target - nums[i].
  3. If seen.containsKey(need), return new int[]{seen.get(need), i}.
  4. Put seen.put(nums[i], i).

Example 2 · Brute force: try every pair of indexes (O(n²) time, O(1) space)

TwoSumBrute.javaJava
import java.util.Arrays;
public class TwoSumBrute {    public static int[] twoSum(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < nums.length; j++) {                if (nums[i] + nums[j] == target) {                    return new int[]{i, j};                }            }        }        return new int[]{-1, -1};    }
    public static void main(String[] args) {        int[] nums1 = {2, 11, 7, 15};        System.out.println("Target 9: " + Arrays.toString(twoSum(nums1, 9)));        int[] nums2 = {3, 3};        System.out.println("Target 6 on [3, 3]: " + Arrays.toString(twoSum(nums2, 6)));    }}
Output
Target 9: [0, 2]
Target 6 on [3, 3]: [0, 1]

What this code does

  • It tests every pair, about n × n / 2 additions, and returns the original indexes because nothing is sorted.
  • For each number the inner loop only asks "does target - nums[i] exist?". A map can answer that question in O(1) instead of by scanning.

Example 3 · Optimal: one pass with a HashMap of value to index (O(n) time, O(n) space)

TwoSumMapDemo.javaJava
import java.util.Arrays;import java.util.HashMap;import java.util.Map;
public class TwoSumMapDemo {    public static int[] twoSum(int[] nums, int target) {        Map<Integer, Integer> seen = new HashMap<>();        for (int i = 0; i < nums.length; i++) {            int complement = target - nums[i];            if (seen.containsKey(complement)) {                return new int[]{seen.get(complement), i};            }            seen.put(nums[i], i);        }        return new int[]{-1, -1};    }
    public static void main(String[] args) {        int[] nums1 = {2, 11, 7, 15};        System.out.println("Target 9: " + Arrays.toString(twoSum(nums1, 9)));        int[] nums2 = {3, 3};        System.out.println("Target 6 on [3, 3]: " + Arrays.toString(twoSum(nums2, 6)));    }}
Output
Target 9: [0, 2]
Target 6 on [3, 3]: [0, 1]

What this code does

  • On [3, 3] with target 6, at i = 0 seen is empty so 3 -> 0 is stored. At i = 1, complement 3 is found at index 0, returning [0, 1].
  • Checking seen.containsKey(complement) before seen.put(nums[i], i) prevents using the same index twice.
  • Why it is faster: the map remembers every earlier number and its index, so the "is the partner there?" scan becomes one lookup. It trades O(n) memory for the time saved.

With a Map<Integer, Integer> seen that maps value -> index, we can solve unsorted Two Sum in a single O(n) pass: At index i, we need complement = target - nums[i]. Before putting nums[i] into seen, we check if (seen.containsKey(complement)). If so, {seen.get(complement), i} is our pair! Checking before inserting guarantees we never pair nums[i] with itself (e.g., when target = 6 and nums[i] = 3).

Order of execution

Order one pass of Two Sum

Tap the steps in the order one loop pass runs them.

Grouping anagrams

In Group Anagrams, given an array of strings strs, we want to group all words that are anagrams of each other (e.g., "eat", "tea", "ate") into lists.

Example 4 · Grouping Anagrams using canonical sorted String keys and computeIfAbsent

GroupAnagramsDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class GroupAnagramsDemo {    public static List<List<String>> groupAnagrams(String[] strs) {        Map<String, List<String>> groups = new LinkedHashMap<>();        for (String word : strs) {            char[] chars = word.toCharArray();            Arrays.sort(chars);            String canonicalKey = new String(chars);            groups.computeIfAbsent(canonicalKey, k -> new ArrayList<>()).add(word);        }        return new ArrayList<>(groups.values());    }
    public static void main(String[] args) {        String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};        System.out.println(groupAnagrams(words));    }}
Output
[[eat, tea, ate], [tan, nat], [bat]]

What this code does

  • Sorting the characters of "eat", "tea", and "ate" produces the identical String key "aet".
  • LinkedHashMap preserves the order in which each anagram group was first encountered.

How do we make all anagrams collide into the same map key? By computing a canonical signature for each word:

  • Sorted-char key: Convert the word to char[], sort it (Arrays.sort(ca)), and turn it back into a String (new String(ca)). All of "eat", "tea", and "ate" produce the key "aet". This takes O(L log L) per word of length L.
  • Frequency-signature key: Count 'a'..'z' in char[26] and new String(counts) (or "#1#0#0..."). This takes O(L) per word. Once we have the canonical key key, a one-line groups.computeIfAbsent(key, k -> new ArrayList<>()).add(word) appends the word to its group!
Never use a raw char[] or int[] as a HashMap key in Java! Arrays in Java do not override Object.equals or Object.hashCode (they hash by memory address). Always convert the sorted char[] to a String (new String(ca)) or use Arrays.toString(counts).

Next step

Check your understanding

10 quick questions