Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 1

Counting, Grouping and Complement Lookups

Replace quadratic nested scans with O(n) hash-table patterns using Counter, defaultdict, dict, and set—frequency histograms, one-pass complement lookup, canonical grouping keys, and linear sequence-start scanning.

Contentsand lesson path

What you will learn

  • Solve counting, deduplication, grouping and complement-lookup problems (such as two-sum and anagram groups) in O(n) with dict, set, Counter and defaultdict.

Prerequisites: Complexity Analysis

01. The problem

Whenever an algorithm repeatedly asks "have I seen something matching x before?" or "how often has x appeared?" inside a loop, scanning a list on each step takes O(n) per query and drags the function to O(n^2). Building on Building Strings Without Quadratic Traps and Lab: Build a Chained Hash Map, you can trade O(n) extra memory for O(1) expected lookups and solve four classic tasks in O(n) expected time.

Our constraint across the examples below: keep time O(n) expected for inputs up to n = 10^5 (ruling out O(n^2) pairwise loops and O(n log n) sorting on longest_consecutive), handle duplicate values safely, and ensure every lookup key is hashable and unambiguous.

Simplification note: we treat dict, set, Counter, and defaultdict lookups as O(1) expected time; as shown in earlier lessons, that relies on well-distributed hashes and bounded load factors.

02. Step 1: frequency maps (Counter vs defaultdict) and complement lookup

For counting occurrences, collections.Counter(codes) builds a frequency map in one O(n) pass and exposes helpers like .most_common(k) (which runs in O(n log k) via a heap when k is given, or O(n log n) when sorting all keys). Notice a subtle and critical difference between Counter and defaultdict(int): reading a missing key freq["E503"] on a Counter returns 0 without inserting "E503" into the map, whereas reading dd["E503"] on a defaultdict(int) silently calls int() and inserts "E503": 0. If you probe candidate keys inside a for k in dd: loop, defaultdict(int) mutates its own size and raises RuntimeError: dictionary changed size during iteration!

Next, look at two_sum_indices(nums, target): return two distinct indices i != j with nums[i] + nums[j] == target. Pairwise loops cost O(n^2), and sorting (val, idx) pairs costs O(n log n). Instead, scan once and ask whether the complement need = target - x appeared at an earlier index. Trace nums = [42, 7, 15, 29] with target = 36:

  • At i = 0 (x = 42): need = 36 - 42 = -6 is not in seen ({}), so record seen[42] = 0.
  • At i = 1 (x = 7): need = 36 - 7 = 29 is not in seen ({42: 0}), so record seen[7] = 1.
  • At i = 2 (x = 15): need = 36 - 15 = 21 is not in seen, so record seen[15] = 2.
  • At i = 3 (x = 29): need = 36 - 29 = 7 is in seen (seen[7] == 1), so return (1, 3) immediately.

Check if need in seen: before assigning seen[x] = i! If you wrote seen[x] = i first, x = 18 with target = 36 would pair with itself and wrongly return (i, i)—whereas checking first restricts seen to strictly earlier indices 0 .. i - 1 while still allowing a second 18 later in the list to pair with the first.

Python · Counter frequency checks and one-pass two_sum_indices
from collections import Counter


def two_sum_indices(nums: list[int], target: int) -> tuple[int, int] | None:
    seen: dict[int, int] = {}
    for i, x in enumerate(nums):
        need = target - x
        if need in seen:
            return (seen[need], i)
        seen[x] = i
    return None


codes = ["E404", "E500", "E404", "E429", "E404", "E500"]
freq = Counter(codes)
print("top 2 errors:", freq.most_common(2))
print("missing E503 via Counter:", freq["E503"], "keys:", len(freq))
print("two_sum([42, 7, 15, 29], 36):", two_sum_indices([42, 7, 15, 29], 36))
Expected output
top 2 errors: [('E404', 3), ('E500', 2)]
missing E503 via Counter: 0 keys: 3
two_sum([42, 7, 15, 29], 36): (1, 3)

Look at missing E503 via Counter: 0 keys: 3: querying "E503" left len(freq) at 3, whereas a defaultdict(int) would have grown to 4 keys.

03. Step 2: canonical grouping keys, deduplication and linear run-starts

In group_anagrams(words), words share a group if and only if they contain identical characters with identical counts. Here collections.defaultdict(list) shines: groups[key].append(w) creates an empty list on first write without an if key not in groups: guard. As the canonical key, tuple(sorted(w)) captures exact character counts while remaining immutable and hashable (costing O(k log k) per word of length k, or O(k) with a 26-count tuple when restricted to lowercase ASCII). Why not frozenset(w)? Because sets drop multiplicities, falsely merging "moon" and "mon" into the same group. Note also how Counter complements defaultdict(list): if you only need to compare whether two texts share identical character frequencies (Counter(a) == Counter(b)), Counter checks equality in O(k) time.

For deduplication, set(events) removes duplicates in O(n) expected time, yet iterating over a set loses original arrival order because slots follow hash order rather than insertion order. When first-seen order matters (in Python 3.7+), list(dict.fromkeys(events)) keeps each unique item once in O(n) expected time while preserving insertion order, or you can maintain a seen = set() and append unseen items to a result list.

Finally, in longest_consecutive(nums), given [45, 12, 90, 9, 11, 10], find the longest consecutive integer run (9, 10, 11, 12 -> length 4) in O(n) expected time without O(n log n) sorting. Put every value into seen = set(nums) for O(1) membership tests, then start counting upward (cur + 1, cur + 2, ...) only when x - 1 not in seen. Trace why that single condition keeps the nested while loop linear: 10, 11, and 12 all see x - 1 in seen, so they skip immediately in O(1); only 9 (8 not in seen), 45 (44 not in seen), and 90 (89 not in seen) launch upward walks, touching 9, 10, 11, 12, 45, and 90 once each (O(n) total expected work).

Python · anagram grouping, order-preserving deduplication, and linear run-starts
from collections import defaultdict


def group_anagrams(words: list[str]) -> list[list[str]]:
    groups: defaultdict[tuple[str, ...], list[str]] = defaultdict(list)
    for w in words:
        groups[tuple(sorted(w))].append(w)
    return list(groups.values())


def longest_consecutive(nums: list[int]) -> int:
    seen = set(nums)
    best = 0
    for x in seen:
        if x - 1 not in seen:
            cur = x
            while cur in seen:
                cur += 1
            best = max(best, cur - x)
    return best


events = ["login", "view", "login", "pay", "view"]
dedup_ordered = list(dict.fromkeys(events))
print("dedup ordered:", dedup_ordered)
tags = ["care", "race", "acre", "post", "stop", "tops", "mint"]
print("group_anagrams:", group_anagrams(tags))
print("longest_consecutive:", longest_consecutive([45, 12, 90, 9, 11, 10]))
Expected output
dedup ordered: ['login', 'view', 'pay']
group_anagrams: [['care', 'race', 'acre'], ['post', 'stop', 'tops'], ['mint']]
longest_consecutive: 4

Notice the contrast between the two deduplication patterns above: dedup_ordered used dict.fromkeys(events) to drop duplicate "login" and "view" events without scrambling sequence order, whereas seen = set(nums) in longest_consecutive ignores order intentionally so 10,000 duplicate copies of 9 collapse into one membership entry and the outer loop visits 9 only once.

When NOT to use hash grouping or defaultdict: if nums in two_sum_indices is already sorted and memory is tight, converging two pointers in Two Pointers & Sliding Window runs in O(n) time and O(1) extra space without a dict. Similarly, if you need grouped keys returned in sorted lexicographical order or queried by prefix range, hash buckets scatter keys so you still pay to sort them afterwards.

04. Check your understanding

Practice check · 3 questions

Counting, grouping and complement patterns

Predict outputs, runtime traps and container semantics.

Q1. While scanning `for k in counts:`, your code checks `if counts[k + "x"] == 0:` to detect missing neighbour keys. Why does `Counter` work cleanly while `defaultdict(int)` crashes?
Q2. Suppose you rewrite `longest_consecutive` to loop `for x in nums:` (the original list, not `seen`) while keeping `if x - 1 not in seen:`. On what input does it degrade to `O(n^2)`?
Q3. In `two_sum_indices([2, 6, 6, 10], 12)`, both `2 + 10` and `6 + 6` sum to `12`. Which pair does the one-pass dict function return, and why?
Practice only: not graded, not saved, not evidence.

05. Apply it

Write a pytest suite for group_anagrams and longest_consecutive covering empty lists [], negative runs ([-3, -2, -1]), and duplicate inputs, and verify longest_consecutive against a sorting reference implementation across random inputs.

Next, see when custom keys fail with TypeError and how adversarial inputs break O(1) lookup in Custom Keys and Adversarial Inputs.

06. Review prompt

Without looking back:

  1. Why must two_sum_indices check target - x in seen before assigning seen[x] = i?
  2. When should you prefer Counter over defaultdict(int) for read-heavy frequency checks?
  3. Explain why longest_consecutive stays O(n) expected despite nesting a while loop inside a for loop.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check