Hash Maps and Hash Sets in Practice: Frequency Counting and Two-Sum Patterns

Learn the hash map patterns behind frequency counting, Two Sum, group anagrams, and longest consecutive sequence, with tested Python and Java code.

Executive Summary: Most interview problems that a hash table solves fall into four hash map patterns: counting, complement lookup, grouping by a canonical key, and set membership. Each one replaces an inner loop with an O(1) average-case lookup, turning O(n^2) brute force into O(n) average time at the cost of O(n) extra space. The hard part is never the container.
Hash map patterns diagram showing a one-pass scan that stores seen values in a hash map and looks up each complement

A classic interview moment: the candidate solves Two Sum with a hash map, runs the example, and it passes. Then the interviewer types the input [4, 1] with target 8. The code returns index 0 twice, pairing the 4 with itself. The bug is one line out of order: the code stored the value before it looked for its partner.

Hash map patterns are reusable ways of using a hash map (key to value) or a hash set (keys only) to remember what you have seen, so you never search for it again. A hash map answers “what do I know about this key?” in O(1) average time. A hash set answers “have I seen this key?” in the same time. Everything here builds on those two questions.

The code targets Python 3.12 and Java 21, using dict, set, Counter, and defaultdict on one side and HashMap, HashSet, getOrDefault, merge, and computeIfAbsent on the other. Big-O describes how running time grows with input size. If you want the internals behind the O(1) claim, including why the worst case is O(n), read the guide to hash table internals.

My position: choose the key before you write the loop. Every hash map pattern here differs only in what it uses as the key and what it stores as the value. Candidates who start typing for before they name the key usually end up with the wrong one.

How to recognize when hash map patterns apply

The input is usually an unsorted array or string, and the brute force has a nested loop. The inner loop searches for something: a partner, a duplicate, or another item with the same property. That inner search is what a hash table removes.

  • “How many times does each…” points to frequency counting.
  • “Find two elements that sum to…” on unsorted input points to complement lookup.
  • “Group items that are equivalent…” points to grouping by a canonical key.
  • “Does a value exist…” asked many times points to a hash set.
  • “In O(n) time” with unsorted input rules out sorting, which costs O(n log n), and leaves hashing as the usual answer.

One test separates these problems from their neighbors. If the answer depends on positions being next to each other, such as a contiguous subarray or substring, you likely need a window or prefix sums alongside the map. If position does not matter, a map or set alone usually does the job.

The toolkit in Python and Java

Both languages give you the same four tools with different names. Knowing the idiom for each saves lines and prevents the most common bugs.

Job Python 3.12 Java 21 Watch out for
Count occurrences Counter(items) or d[k] = d.get(k, 0) + 1 map.merge(k, 1, Integer::sum) merge removes the key if the function returns null
Read with a default d.get(k, 0); Counter returns 0 for missing keys map.getOrDefault(k, 0) Neither inserts the key
Group into lists defaultdict(list) map.computeIfAbsent(k, x -> new ArrayList<>()).add(v) Reading dd[k] on a defaultdict inserts an empty list
Membership set HashSet set.add in Java returns false for a duplicate, a free duplicate check
Insertion order Every dict keeps it (guaranteed since 3.7) LinkedHashMap; HashMap has no order Tests that print a HashMap can flake

The Python collections documentation spells out two behaviors worth memorizing. Counter returns zero for a missing item instead of raising KeyError, and most_common orders ties by first appearance. On the Java side, the Java Map interface documentation defines merge: if the key is absent it stores the given value, otherwise it stores the function’s result, and a null result removes the mapping.

The core invariant: look before you insert

Every one-pass hash map pattern keeps the same invariant. When you process element j, the map holds exactly what you learned from elements 0 to j - 1. You query the map first, then add element j. That order guarantees that element j never matches itself.

 nums  = [ 4 | 11 |  7 |  2 ]      target = 9
 index     0    1    2    3
                          ^
                          j = 3, x = 2, need = 9 - 2 = 7

 seen (built from indices 0..2, before touching j):
 +-------+-------+
 | value | index |
 +-------+-------+
 |   4   |   0   |
 |  11   |   1   |
 |   7   |   2   |  <- need = 7 found, answer (2, 3)
 +-------+-------+

The reusable template has four steps. Derive a key from the current element. Query the map with it. Act on the result. Finally, record the current element. Swap the key and value choices and you get each pattern below.

Pattern 1: frequency counting

Frequency counting builds a map from item to the number of times it appears. It turns questions about “how many” into constant-time reads. It also powers anagram checks, first unique character, majority element, and top-k frequent items.

Two counting problems show the range. An anagram check counts characters in one string and subtracts them for the other, failing the moment a count goes negative. First unique character needs two passes: count everything first, then scan the string in its original order and return the first character with count 1. For a deeper comparison of anagram checks by sorting and by counting, see the guide to anagram checks by sorting vs counting.

In Python:

from collections import Counter


def is_anagram(a: str, b: str) -> bool:
    """True when a and b use the same characters with the same counts."""
    if len(a) != len(b):
        return False
    counts: dict[str, int] = {}
    for ch in a:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in b:
        counts[ch] = counts.get(ch, 0) - 1
        if counts[ch] < 0:
            return False  # b uses ch more often than a does
    return True


def first_unique_index(s: str) -> int:
    """Index of the first character that appears exactly once, or -1."""
    counts = Counter(s)  # pass 1: count everything
    for i, ch in enumerate(s):  # pass 2: scan in the original order
        if counts[ch] == 1:
            return i
    return -1


def most_frequent(words: list[str], k: int) -> list[str]:
    """The k most frequent words; ties keep first-seen order (Counter guarantees it)."""
    return [word for word, _ in Counter(words).most_common(k)]


if __name__ == "__main__":
    # Normal cases
    assert is_anagram("listen", "silent")
    assert not is_anagram("listen", "listens")
    assert first_unique_index("swiss") == 1  # 'w'
    assert most_frequent(["go", "py", "go", "java", "py", "go"], 2) == ["go", "py"]

    # Empty and single-element inputs
    assert is_anagram("", "")
    assert first_unique_index("") == -1
    assert first_unique_index("z") == 0
    assert most_frequent([], 3) == []

    # Duplicates: same letters, different counts
    assert not is_anagram("aab", "abb")
    assert first_unique_index("aabb") == -1

    # Edge case: Counter returns 0 for a missing key instead of raising KeyError
    c = Counter("abc")
    assert c["zzz"] == 0 and "zzz" not in c  # reading does not insert
    print("all tests passed")

The same in Java:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class FrequencyCounting {

    static boolean isAnagram(String a, String b) {
        if (a.length() != b.length()) {
            return false;
        }
        Map<Character, Integer> counts = new HashMap<>();
        for (char ch : a.toCharArray()) {
            counts.merge(ch, 1, Integer::sum);
        }
        for (char ch : b.toCharArray()) {
            int left = counts.getOrDefault(ch, 0) - 1;
            if (left < 0) {
                return false; // b uses ch more often than a does
            }
            counts.put(ch, left);
        }
        return true;
    }

    static int firstUniqueIndex(String s) {
        Map<Character, Integer> counts = new HashMap<>();
        for (char ch : s.toCharArray()) {
            counts.merge(ch, 1, Integer::sum); // pass 1: count
        }
        for (int i = 0; i < s.length(); i++) {
            if (counts.get(s.charAt(i)) == 1) { // pass 2: original order
                return i;
            }
        }
        return -1;
    }

    static List<String> mostFrequent(List<String> words, int k) {
        // LinkedHashMap keeps first-seen order so ties stay stable after a stable sort.
        Map<String, Integer> counts = new LinkedHashMap<>();
        for (String w : words) {
            counts.merge(w, 1, Integer::sum);
        }
        List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());
        entries.sort((x, y) -> Integer.compare(y.getValue(), x.getValue()));
        List<String> result = new ArrayList<>();
        for (int i = 0; i < Math.min(k, entries.size()); i++) {
            result.add(entries.get(i).getKey());
        }
        return result;
    }

    private static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        // Normal cases
        check(isAnagram("listen", "silent"), "anagram");
        check(!isAnagram("listen", "listens"), "length differs");
        check(firstUniqueIndex("swiss") == 1, "first unique");
        check(mostFrequent(List.of("go", "py", "go", "java", "py", "go"), 2)
                .equals(List.of("go", "py")), "top 2");

        // Empty and single-element inputs
        check(isAnagram("", ""), "empty anagram");
        check(firstUniqueIndex("") == -1, "empty unique");
        check(firstUniqueIndex("z") == 0, "single unique");
        check(mostFrequent(List.of(), 3).isEmpty(), "empty top k");

        // Duplicates: same letters, different counts
        check(!isAnagram("aab", "abb"), "count mismatch");
        check(firstUniqueIndex("aabb") == -1, "no unique");

        // Edge case: merge removes the key when the function returns null
        Map<String, Integer> m = new HashMap<>();
        m.merge("x", 1, Integer::sum);
        m.merge("x", 1, (oldV, one) -> null);
        check(!m.containsKey("x"), "merge returning null removes the mapping");
        System.out.println("PASS");
    }
}

The two-pass shape of first unique character is the twist to remember. A single pass cannot know whether a character repeats later, so you count everything before you decide anything. The extra space is O(k), where k is the number of distinct characters, which is at most the alphabet size.

Pattern 2: complement lookup and Two Sum

Two Sum asks for two positions whose values add up to a target. The brute force checks every pair, which is O(n^2) and too slow at n = 10^5. Instead, for each value x, ask whether its complement target - x already appeared. A map from value to index answers that in O(1) average time.

The key is the value, because that is what you search for. The stored value is the index, because that is what you must return. That one decision is the whole solution.

In Python:

from typing import Optional


def two_sum(nums: list[int], target: int) -> Optional[tuple[int, int]]:
    """Indices (i, j) with i < j and nums[i] + nums[j] == target, or None."""
    seen: dict[int, int] = {}  # value -> index of an earlier element
    for j, x in enumerate(nums):
        need = target - x
        if need in seen:  # look first...
            return seen[need], j
        seen[x] = j  # ...then insert, so x never pairs with itself
    return None


if __name__ == "__main__":
    # Normal case
    assert two_sum([4, 11, 7, 2], 9) == (2, 3)
    # Negative numbers and zero
    assert two_sum([-3, 8, 0, 5], 5) == (0, 1)
    # Empty and single-element inputs
    assert two_sum([], 4) is None
    assert two_sum([4], 8) is None  # one 4 cannot pair with itself
    # Duplicates: two equal values that sum to the target
    assert two_sum([5, 1, 5], 10) == (0, 2)
    # No answer
    assert two_sum([1, 2, 3], 100) is None
    print("all tests passed")

The same in Java:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class TwoSum {

    /** Returns {i, j} with i < j and nums[i] + nums[j] == target, or null. */
    static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> seen = new HashMap<>(); // value -> earlier index
        for (int j = 0; j < nums.length; j++) {
            Integer i = seen.get(target - nums[j]); // look first...
            if (i != null) {
                return new int[] {i, j};
            }
            seen.put(nums[j], j); // ...then insert
        }
        return null;
    }

    private static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        check(Arrays.equals(twoSum(new int[] {4, 11, 7, 2}, 9), new int[] {2, 3}), "normal");
        check(Arrays.equals(twoSum(new int[] {-3, 8, 0, 5}, 5), new int[] {0, 1}), "negatives");
        check(twoSum(new int[] {}, 4) == null, "empty");
        check(twoSum(new int[] {4}, 8) == null, "single element cannot pair with itself");
        check(Arrays.equals(twoSum(new int[] {5, 1, 5}, 10), new int[] {0, 2}), "duplicates");
        check(twoSum(new int[] {1, 2, 3}, 100) == null, "no answer");
        // Large values: the boxed Integer from get() is compared with != null, never ==
        check(Arrays.equals(twoSum(new int[] {1000, 2000}, 3000), new int[] {0, 1}), "large");
        System.out.println("PASS");
    }
}

Dry run on [4, 11, 7, 2] with target 9

j x need = 9 – x need in seen? seen after the step
0 4 5 no {4: 0}
1 11 -2 no {4: 0, 11: 1}
2 7 2 no {4: 0, 11: 1, 7: 2}
3 2 7 yes, at index 2 return (2, 3)

The duplicate bug: wrong, then right

The wrong version inserts first and checks second. In Python:

def two_sum_wrong(nums: list[int], target: int) -> tuple[int, int] | None:
    seen: dict[int, int] = {}
    for j, x in enumerate(nums):
        seen[x] = j                      # inserted too early
        if target - x in seen:
            return seen[target - x], j   # [4, 1], target 8 returns (0, 0)
    return None

The right version swaps those two lines. In Python:

def two_sum_right(nums: list[int], target: int) -> tuple[int, int] | None:
    seen: dict[int, int] = {}
    for j, x in enumerate(nums):
        if target - x in seen:           # look first
            return seen[target - x], j
        seen[x] = j                      # then insert
    return None

The input [4, 1] with target 8 breaks the wrong version, because 4 finds itself. The right version also handles genuine duplicates. With [5, 1, 5] and target 10, the second 5 finds the first one at index 0. The map stores one index per value, and that is enough, because you only need the earliest partner.

Here is the non-obvious connection textbooks skip. Two Sum is a hash join in miniature. The PostgreSQL planner documentation describes a hash join as loading one relation into a hash table keyed on the join attributes, then probing it with each row of the other relation. Your seen map is the build side, and each target - x is a probe.

Pattern 3: grouping by a canonical key

Grouping maps every item to a canonical form, a key that equal-in-spirit items share. All anagrams of “tea” share the same letter counts. All strings with the same shape share a shape signature. The map then goes from canonical key to the list of items with that key.

Two canonical keys work for group anagrams. Sorting the letters costs O(L log L) per word of length L. A 26-slot count vector costs O(L), but it must become hashable first. In Python, convert the list to a tuple. In Java, an int[] uses identity equals, so two equal arrays are different keys. Build a string such as "1#0#2#..." instead.

Pattern 4: set membership and longest consecutive sequence

Longest consecutive sequence asks for the longest run of integers like 1, 2, 3, 4 hidden anywhere in an unsorted array. Sorting solves it in O(n log n). A hash set solves it in O(n) average time with one trick: only start counting from a value v when v - 1 is absent.

That check is what keeps the algorithm linear. Without it, every element of a run would count the rest of its run, and a single run of length n would cost O(n^2). With it, only run starts enter the inner loop, so each value is visited by an inner loop at most once.

Grouping and membership in Python:

from collections import defaultdict


def group_anagrams(words: list[str]) -> list[list[str]]:
    """Group words that are anagrams; groups appear in first-seen order."""
    groups: defaultdict[tuple[int, ...], list[str]] = defaultdict(list)
    for w in words:
        counts = [0] * 26  # assumes lowercase a-z
        for ch in w:
            counts[ord(ch) - ord("a")] += 1
        groups[tuple(counts)].append(w)  # a list is unhashable; a tuple is fine
    return list(groups.values())


def longest_consecutive(nums: list[int]) -> int:
    """Length of the longest run of consecutive integers, in any order."""
    values = set(nums)
    best = 0
    for v in values:
        if v - 1 in values:
            continue  # v is not the start of a run; its start will count it
        length = 1
        while v + length in values:
            length += 1
        best = max(best, length)
    return best


if __name__ == "__main__":
    # Normal cases
    assert group_anagrams(["tea", "ate", "tan", "eat", "nat", "bat"]) == [
        ["tea", "ate", "eat"], ["tan", "nat"], ["bat"]]
    assert longest_consecutive([10, 4, 20, 1, 3, 2]) == 4  # 1, 2, 3, 4

    # Empty and single-element inputs
    assert group_anagrams([]) == []
    assert group_anagrams([""]) == [[""]]
    assert longest_consecutive([]) == 0
    assert longest_consecutive([7]) == 1

    # Duplicates
    assert group_anagrams(["ab", "ba", "ab"]) == [["ab", "ba", "ab"]]
    assert longest_consecutive([2, 2, 3, 3, 4]) == 3

    # Edge case: negatives and a long run must stay linear
    assert longest_consecutive([-1, 0, 1, -2]) == 4
    assert longest_consecutive(list(range(200_000, 0, -1))) == 200_000
    print("all tests passed")

The same in Java:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Grouping {

    static List<List<String>> groupAnagrams(List<String> words) {
        // LinkedHashMap keeps groups in first-seen order.
        Map<String, List<String>> groups = new LinkedHashMap<>();
        for (String w : words) {
            int[] counts = new int[26]; // assumes lowercase a-z
            for (char ch : w.toCharArray()) {
                counts[ch - 'a']++;
            }
            // int[] uses identity equals, so build a String key from the counts.
            StringBuilder key = new StringBuilder();
            for (int c : counts) {
                key.append(c).append('#');
            }
            groups.computeIfAbsent(key.toString(), k -> new ArrayList<>()).add(w);
        }
        return new ArrayList<>(groups.values());
    }

    static int longestConsecutive(int[] nums) {
        Set<Integer> values = new HashSet<>();
        for (int x : nums) {
            values.add(x);
        }
        int best = 0;
        for (int v : values) {
            if (values.contains(v - 1)) {
                continue; // not the start of a run
            }
            int length = 1;
            while (values.contains(v + length)) {
                length++;
            }
            best = Math.max(best, length);
        }
        return best;
    }

    private static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        check(groupAnagrams(List.of("tea", "ate", "tan", "eat", "nat", "bat")).equals(List.of(
                List.of("tea", "ate", "eat"), List.of("tan", "nat"), List.of("bat"))), "group");
        check(longestConsecutive(new int[] {10, 4, 20, 1, 3, 2}) == 4, "run of 4");

        check(groupAnagrams(List.of()).isEmpty(), "empty group");
        check(groupAnagrams(List.of("")).equals(List.of(List.of(""))), "empty word");
        check(longestConsecutive(new int[] {}) == 0, "empty run");
        check(longestConsecutive(new int[] {7}) == 1, "single run");

        check(groupAnagrams(List.of("ab", "ba", "ab")).equals(List.of(List.of("ab", "ba", "ab"))),
                "duplicate words");
        check(longestConsecutive(new int[] {2, 2, 3, 3, 4}) == 3, "duplicate values");

        check(longestConsecutive(new int[] {-1, 0, 1, -2}) == 4, "negatives");
        int[] big = new int[200_000];
        for (int i = 0; i < big.length; i++) {
            big[i] = big.length - i;
        }
        check(longestConsecutive(big) == 200_000, "long run stays linear");
        System.out.println("PASS");
    }
}

Complexity of the hash map patterns

All times below are average case. Each lookup is O(1) on average but O(n) in the worst case if many keys collide, so every bound can degrade under adversarial hashing.

Problem Pattern Time (average) Extra space
Count frequencies Counting O(n) O(k) distinct keys
Valid anagram Counting O(n) O(k), at most the alphabet size
First unique character Counting, two passes O(n) O(k)
Top k frequent with most_common(k) Counting plus a heap O(n log k) O(n)
Two Sum Complement lookup O(n) O(n)
Group anagrams Canonical key O(n * L) with counts, O(n * L log L) sorted O(n * L)
Longest consecutive sequence Set membership O(n) O(n)

None of these solutions recurse, so the call stack stays O(1). The space column is the honest trade: every pattern buys its speed with a map that can grow as large as the input.

Where this shows up in real systems

  • Database hash joins. PostgreSQL can join two tables by building a hash table on one side and probing it with the other, as its planner documentation describes. That is complement lookup at the scale of millions of rows.
  • Content-addressed storage. The Git internals chapter on objects describes Git’s core as a key-value store, where the key comes from hashing the content. Identical files produce the same key and are stored once, which is set-based deduplication.
  • Metrics and log aggregation. Counting requests per endpoint or errors per code is frequency counting. A map from label to count is the simplest correct implementation, and its memory grows with the number of distinct labels.

How to explain it in an interview

Walk through the problem in this order, out loud.

  1. Brute force. State the nested loop and its O(n^2) cost.
  2. The bottleneck. Point at the inner loop and say what it searches for.
  3. The insight. Name the key and the value: “I’ll map each value to its index.”
  4. The optimized solution. Code one pass, looking up before inserting.
  5. Complexity. Say “O(n) average time, O(n) space,” and mention the worst case.
  6. Edge cases. Empty input, one element, duplicates, and negative numbers.

Interviewers often follow up with variants. They may ask what changes if the array is sorted (two pointers, O(1) space), or for all pairs instead of one. They may also ask how to handle a stream too large for memory.

A mistake I see often when candidates use these patterns: they reach for the map, then hesitate over what to store. Some store a boolean where they needed an index, then bolt on a second loop to find the index. The strong candidates say the key and value out loud before writing code. That habit also catches the duplicate bug, because naming “value to earlier index” makes “earlier” explicit.

Decision framework for hash map patterns

  1. What does the inner loop search for? That thing becomes your key.
  2. What must you return or accumulate? That becomes the value: an index, a count, or a list.
  3. Do you need only existence? Use a set and skip the value.
  4. Can an element match itself? If not, look up before you insert.
  5. Must you see everything before deciding? If yes, use two passes: count first, decide second.
  6. Is the key a list or array? Convert it to a tuple in Python or a string in Java.

When not to use a hash map

  • The input is already sorted. Pair problems on sorted arrays need only opposite-direction two pointers on sorted arrays, which use O(1) extra space instead of O(n).
  • The answer depends on contiguous ranges. “Longest substring with no repeats” needs a map inside a window, covered by variable-size sliding windows. “Count subarrays that sum to k” pairs a map with running totals, covered by subarray sums with prefix sums and a hash map.
  • The key range is tiny and fixed. For lowercase letters, an int[26] beats a map on speed and memory, and two arrays compare with one equality check.

Common mistakes

  • Inserting before looking up. The element matches itself. Input [4, 1] with target 8 returns (0, 0).
  • Comparing boxed counts with == in Java. Integer is only guaranteed to cache -128 to 127, so == on two separate counts of 200 can return false. Use Objects.equals or unbox to int.
  • Reading a defaultdict to check a key. if dd[k]: inserts k with an empty list, and the map grows with every miss. Use k in dd or dd.get(k).
  • Using a mutable list as a key. Python raises TypeError: unhashable type: 'list'. In Java, an int[] key compiles but matches only the same array object.
  • Counting every element in longest consecutive sequence. Skipping the v - 1 check gives O(n^2) on one long run such as 1 to 100,000.
  • Relying on HashMap iteration order. Output that “looks sorted” for small integer keys breaks on other inputs. Use LinkedHashMap or sort explicitly.

Practice problems

Problem Difficulty The twist
Valid Anagram Easy Count up for one string, down for the other; fail on a negative count
First Unique Character in a String Easy Two passes, because a later repeat can disqualify an early character
Two Sum Easy Map value to index; look up the complement before inserting
Ransom Note Easy Count the supply, then spend from it; any negative count fails
Group Anagrams Medium A canonical key (sorted letters or a count tuple) groups the words
Top K Frequent Elements Medium Count first, then select the k largest counts with a heap or buckets
Longest Consecutive Sequence Medium A set plus the “only start at a run’s first value” rule keeps it linear
Subarray Sum Equals K Medium The key is a running prefix total, and the value is how often it occurred

Key takeaways

  • Four hash map patterns cover most problems: counting, complement lookup, canonical-key grouping, and set membership.
  • Name the key and the value before writing the loop; the rest follows.
  • In one-pass solutions, look up before you insert so an element never matches itself.
  • Use Counter, defaultdict, merge, and computeIfAbsent to keep counting and grouping code short and correct.
  • Make keys hashable: tuples in Python, strings or records in Java, never raw lists or arrays.
  • Quote O(n) average time and O(n) space, and know that sorted input lets you drop the map.

Frequently Asked Questions

Why does Two Sum use a hash map instead of sorting?

Two Sum must return original indices, and sorting moves elements, so you would need extra bookkeeping. A hash map from value to index finds each complement in O(1) average time, giving O(n) overall versus O(n log n) for sorting. If the input is already sorted, two pointers solve it with O(1) extra space.

What is the difference between a hash map and a hash set?

A hash map stores key and value pairs, so it can answer what you know about a key, such as its count or index. A hash set stores keys only and answers whether a key is present. Use a set when existence is all you need.

When should I use Counter instead of a regular dict in Python?

Use Counter when you count items, because it builds counts from any iterable in one call and returns zero for missing keys. It also provides most_common for top k queries. A regular dict with get and a default works too but takes more code.

Why is longest consecutive sequence O(n) when it has a nested loop?

The inner loop only runs from values that start a run, meaning the value just below them is absent. Each value is therefore walked by at most one inner loop, so the total work across all loops is linear. Without that start check, the same code becomes quadratic on one long run.

Decide the key before you write the loop

Every pattern here is the same move: replace a search with a lookup by choosing the right key. Counting keys on the item, Two Sum on the value you need, grouping on a canonical form, and runs on set membership. For the data structures and patterns around these, browse the DSA Playbook hub. Rule of thumb: if your inner loop searches for something, that something is your key.

Originally posted on 1 December 2026 and post last modified on 3 December 2026

Coding Interviews Data Structures Hash Maps Hashing

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *