Category I · 25 Problems

defaultdict Mastery

From defaultdict(int) to nested lambdas, graph adjacency lists, and LeetCode problems. Every pattern you need — predict outputs, spot gotchas, and write real solutions.

Problems: 25
Difficulty: Easy → Hard
Key libs: collections.defaultdict · lambda · Counter
25Problems
6Sections
5Factory Types
3LeetCode
The core idea: defaultdict(factory) auto-creates a default value when you access a missing key. The factory is a callable — called with no arguments to produce the default. This eliminates the KeyError and replaces clunky if key not in d: d[key] = ... boilerplate.

Rule of thumb: int → counters. list → grouping. set → unique grouping. lambda → any custom default.

Mental Model — dict vs defaultdict

Regular dict — crashes
d = {} d["x"] += 1 # KeyError! # Must write: if "x" not in d: d["x"] = 0 d["x"] += 1
defaultdict(int) — just works
from collections import defaultdict d = defaultdict(int) d["x"] += 1 # auto-init to 0 # Clean, readable, fast
Factory → Default value
int → 0 list → [] set → set() str → "" float → 0.0 lambda: 42 → 42 lambda: {} → {} lambda: defaultdict(int) → nested dd
How it works internally
# When d[key] is missing: # Python calls d.__missing__(key) # Which calls: default_factory() # And stores the result at d[key] # You can override __missing__ # yourself on a plain dict subclass
Section 1 — defaultdict(int) · Counting
Q 01 Predict Output Easy
Basic Counter
from collections import defaultdict

d = defaultdict(int)
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
for w in words:
    d[w] += 1

print(d["apple"])
print(d["banana"])
print(d["mango"])   # key does not exist
print(len(d))
Output
3 2 0 4
Why? defaultdict(int) calls int() — which returns 0 — when a missing key is accessed. So d["mango"] silently creates the key with value 0 and returns it. That's why len(d) is 4 — "mango" was added to the dict the moment you accessed it. This is the most common gotcha: reading a missing key creates it.
Q 02 Multiple Choice Easy
What does the factory do?
from collections import defaultdict
d = defaultdict(int)
print(d["x"])

What is printed, and what happens to d?

Answer: c. When a missing key is accessed, defaultdict calls int() to produce 0, stores it at d["x"], then returns it. The dict is now {"x": 0}. This is different from dict.get("x", 0) which returns 0 without creating the key. Use .get() when you don't want side effects.
Q 03 Predict Output Easy
Nested access trap
from collections import defaultdict

d = defaultdict(int)
d["a"] = 5

print(d["a"])
print(d["b"])
print("b" in d)
print(d.get("c"))
print("c" in d)
Output
5 0 True None False
Key contrast: d["b"] triggers __missing__ → creates "b": 0 → "b" in d is now True. But d.get("c") does NOT trigger __missing__ — it returns None without creating the key. So "c" in d stays False.

Rule: Use d.get(key) when you want to check a value without creating the key.
Q 04 Coding Problem Easy
Character Frequency
Given a string, return a defaultdict(int) with the frequency of each character. Then return the character with the highest frequency. If tied, return the lexicographically smallest.
Example
char_freq("mississippi") → defaultdict: {'m':1, 'i':4, 's':4, 'p':2} → most_frequent: "i" (tied 's' and 'i' at 4, 'i' < 's')
defaultdict(int) sorted + lambda two-key sort
Solution
from collections import defaultdict

def char_freq(s: str):
    # Count every character in one pass
    freq = defaultdict(int)
    for ch in s:
        freq[ch] += 1
    # Two-key sort: highest count first, then lex smallest on tie
    best = sorted(freq, key=lambda ch: (-freq[ch], ch))[0]
    return freq, best
Two-key sort: (-freq[ch], ch) — negative count puts higher counts first; the character string itself breaks ties lexicographically. This is the same pattern as LeetCode 692 Top K Frequent Words.
Section 2 — defaultdict(list) · Grouping
Q 05 Predict Output Easy
Group by first letter
from collections import defaultdict

words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = defaultdict(list)

for w in words:
    groups[w[0]].append(w)

print(groups["a"])
print(groups["b"])
print(groups["z"])
Output
['apple', 'avocado'] ['banana', 'blueberry'] []
Why? defaultdict(list) calls list() — returns [] — for any missing key. Accessing groups["z"] creates an empty list. No KeyError, no pre-check needed. This replaces the pattern: if key not in d: d[key] = [] / d[key].append(...).
Q 06 Multiple Choice Easy
setdefault vs defaultdict
# Option A
d1 = {}
d1.setdefault("x", []).append(1)
d1.setdefault("x", []).append(2)

# Option B
from collections import defaultdict
d2 = defaultdict(list)
d2["x"].append(1)
d2["x"].append(2)

What is d1["x"] and d2["x"]?

Answer: b. Both produce [1, 2]. setdefault returns the existing value if the key exists, so the second call returns the same list (already [1]) and appends 2 to it. defaultdict(list) does the same thing more cleanly — no need to pass the default on every access.

When to use which: defaultdict when you always use the same default type. setdefault when the default might vary per call.
Q 07 Coding Problem Medium
Invert a Dictionary
Given a dict where values might not be unique, invert it so keys become values and values become lists of original keys. Use defaultdict(list).
Example
original = {"a": 1, "b": 2, "c": 1, "d": 3, "e": 2} invert(original) → {1: ["a", "c"], 2: ["b", "e"], 3: ["d"]}
defaultdict(list).items()dict inversion
Solution
from collections import defaultdict

def invert(d: dict) -> dict:
    # Group original keys by their value
    inv = defaultdict(list)
    for k, v in d.items():
        inv[v].append(k)
    return dict(inv)   # convert back to plain dict for clean output
Pattern: Iterate .items(), swap key/value, append to the new list. Without defaultdict, you'd write if v not in inv: inv[v] = [] every time. Converting back with dict(inv) is good practice — callers get a plain dict, not a defaultdict.
Q 08 Coding Problem Medium
Word → Line Numbers Index
Given a list of text lines, build an index mapping each word to the list of line numbers (0-indexed) it appears on. Case-insensitive. Skip punctuation.
Example
lines = ["Hello world", "World of Python", "Hello again"] build_index(lines) → {"hello": [0, 2], "world": [0, 1], "of": [1], "python": [1], "again": [2]}
defaultdict(list)enumeratestr.splitstr.lower
Solution
from collections import defaultdict
import re

def build_index(lines):
    index = defaultdict(list)
    for line_num, line in enumerate(lines):
        # Extract only word characters, lowercase
        words = re.findall(r'\b[a-z]+\b', line.lower())
        for word in words:
            index[word].append(line_num)
    return dict(index)
This is the classic inverted index pattern — the foundation of search engines. defaultdict(list) lets you append line numbers without checking if the word was seen before. re.findall(r'\b[a-z]+\b', ...) cleanly strips punctuation.
Section 3 — defaultdict(set) · Unique Grouping
Q 09 Predict Output Easy
Unique values per key
from collections import defaultdict

d = defaultdict(set)
pairs = [("a", 1), ("b", 2), ("a", 1), ("a", 3), ("b", 2)]
for k, v in pairs:
    d[k].add(v)

print(sorted(d["a"]))
print(sorted(d["b"]))
print(d["c"])
Output
[1, 3] [2] set()
Why defaultdict(set)? When you need to group values per key but want uniqueness. list collects duplicates; set deduplicates automatically. The pair ("a", 1) appears twice but d["a"] holds {1, 3} — only unique values. d["c"] creates an empty set(), shown as set() (not {} — that's an empty dict!).
Q 10 Coding Problem Medium
Graph as Adjacency List
Given a list of undirected edges (u, v), build an adjacency list using defaultdict(set). Then return all neighbours of a given node, sorted.
Example
edges = [(1,2),(1,3),(2,3),(3,4)] graph = build_graph(edges) neighbours(graph, 3) → [1, 2, 4]
defaultdict(set)undirected graphadjacency list
Solution
from collections import defaultdict

def build_graph(edges):
    graph = defaultdict(set)
    for u, v in edges:
        graph[u].add(v)   # undirected — add both directions
        graph[v].add(u)
    return graph

def neighbours(graph, node):
    return sorted(graph[node])  # sorted for deterministic output
Why set instead of list? Sets prevent duplicate edges. If the same edge (1,2) appears twice in input, the graph is still correct — no duplicate neighbours. This is the standard way to build graphs in Python interview problems.
Section 4 — lambda factories · Custom Defaults
Q 11 Predict Output Medium
lambda: constant value
from collections import defaultdict

d = defaultdict(lambda: "unknown")
d["name"] = "Alice"

print(d["name"])
print(d["age"])
print(d["city"])
Output
Alice unknown unknown
lambda: "unknown" is a zero-argument callable that always returns "unknown". Any missing key gets this default. Explicit keys override it normally. This replaces dict.get(key, "unknown") — useful when you're accessing many keys and want a consistent fallback without repeating the default everywhere.
Q 12 Predict Output Medium
lambda: mutable default — gotcha!
from collections import defaultdict

# lambda: [] creates a NEW list for each missing key
d = defaultdict(lambda: [])
d["a"].append(1)
d["b"].append(2)

print(d["a"])
print(d["b"])
print(d["a"] is d["b"])
Output
[1] [2] False
Each key gets its own fresh list. The lambda is called every time a new key is accessed. So d["a"] and d["b"] are two different list objects — is returns False.

Compare this to a common Python gotcha with mutable defaults in function signatures: def f(x=[]): — there, the same list is shared. With defaultdict(lambda: []), each call creates a new list. Safe.

Note: defaultdict(lambda: []) is equivalent to defaultdict(list). Prefer list.
Q 13 Predict Output Medium
lambda: arbitrary starting value
from collections import defaultdict

# Count down from 10 for each new key
d = defaultdict(lambda: 10)
d["x"] -= 3
d["y"] -= 7
d["x"] -= 2

print(d["x"])
print(d["y"])
print(d["z"])
Output
5 3 10
Why? d["x"] starts at 10 (lambda), then -= 3 makes it 7, then -= 2 makes it 5. d["y"] starts at 10, -= 7 → 3. d["z"] is accessed for the first time → lambda returns 10. Nothing else changes it.

This pattern — lambda: N — is useful for problems where new counters start at a non-zero baseline.
Q 14 Coding Problem Medium
Score Tracker with Custom Default
Players start with 100 points. Build a score tracker using defaultdict(lambda: 100). Apply a list of (player, delta) events. Return final scores for all players seen.
Example
events = [("alice", -10), ("bob", +20), ("alice", -5), ("carol", -30)] track_scores(events) → {"alice": 85, "bob": 120, "carol": 70}
defaultdict(lambda)+=dict()
Solution
from collections import defaultdict

def track_scores(events):
    # Each new player starts at 100 automatically
    scores = defaultdict(lambda: 100)
    for player, delta in events:
        scores[player] += delta
    return dict(scores)
Without defaultdict, you'd write: if player not in scores: scores[player] = 100 before every update. The lambda removes that boilerplate entirely. scores[player] += delta reads the current value (100 if new), adds delta, stores back.
Section 5 — Nested defaultdict · Two-Level Grouping
Q 15 Predict Output Medium
defaultdict of defaultdict(int)
from collections import defaultdict

# Two-level: outer key → inner key → count
d = defaultdict(lambda: defaultdict(int))

d["alice"]["python"] += 3
d["alice"]["java"]   += 1
d["bob"]["python"]   += 5

print(d["alice"]["python"])
print(d["alice"]["go"])    # not set yet
print(d["bob"]["python"])
print(list(d.keys()))
Output
3 0 5 ['alice', 'bob']
Two-level nesting: The outer defaultdict uses lambda: defaultdict(int) so each new outer key gets a fresh inner defaultdict(int). d["alice"]["go"] accesses a missing inner key → inner defaultdict returns 0.

Why not defaultdict(defaultdict(int))? That would call defaultdict(int) once and share the same inner dict for all outer keys — a shared-state bug! Always use lambda: defaultdict(int) for nesting, so each key gets its own fresh inner dict.
Q 16 Multiple Choice Hard
The shared-inner-dict bug
from collections import defaultdict

# BUG: defaultdict(int) is evaluated ONCE here
inner = defaultdict(int)
d = defaultdict(inner)   # passing an instance, not a factory!

d["alice"]["python"] += 3
d["bob"]["python"]   += 5

print(d["alice"]["python"])

What does this print — and why is the code wrong?

Answer: b. defaultdict(inner) passes the same defaultdict(int) instance as the factory. When Python calls inner() it calls the defaultdict as a function. A defaultdict is callable and calling it with no args returns 0 (calls its own factory). This means d["alice"] and d["bob"] both get the same inner dict object! So d["alice"]["python"] += 3 and d["bob"]["python"] += 5 both write to the same key, totaling 8.

Fix: Always use lambda: defaultdict(int) — the lambda is called fresh each time, creating a new inner dict.
Q 17 Coding Problem Medium
User → Action → Count
Given a list of (user, action) events, count how many times each user performed each action. Use a nested defaultdict. Return the count for a specific (user, action) pair.
Example
events = [ ("alice", "login"), ("bob", "login"), ("alice", "click"), ("alice", "login"), ("bob", "logout"), ("alice", "click") ] count_actions(events, "alice", "click") → 2 count_actions(events, "bob", "click") → 0
nested defaultdictlambda: defaultdict(int)two-level grouping
Solution
from collections import defaultdict

def build_action_map(events):
    # outer: user → inner: action → count
    action_map = defaultdict(lambda: defaultdict(int))
    for user, action in events:
        action_map[user][action] += 1
    return action_map

def count_actions(events, user, action):
    action_map = build_action_map(events)
    # .get() avoids creating the key if user/action not seen
    return action_map.get(user, {}).get(action, 0)
Pattern: action_map[user][action] += 1 — two bracket accesses, both safe. For querying, use .get() chains to avoid creating keys just from reading. This two-level structure (user → action → count) appears constantly in analytics and log processing problems.
Section 6 — Gotchas · Common Mistakes
Q 18 Predict Output Medium
Iterating creates keys!
from collections import defaultdict

d = defaultdict(int)
keys_to_check = ["a", "b", "c"]

for k in keys_to_check:
    if d[k] == 0:           # accessing d[k] creates the key!
        pass

print(list(d.keys()))
Output
['a', 'b', 'c']
Gotcha: Even though you never wrote to these keys, just reading them with d[k] triggered __missing__ and created them with value 0.

Fix: Use d.get(k, 0) == 0 to check without creating the key. Or use k in d to check existence. Only use d[k] when you intend to create the key.
Q 19 Multiple Choice Medium
defaultdict(None) — what happens?
from collections import defaultdict
d = defaultdict(None)
d["a"] = 1
print(d["b"])
Answer: c) KeyError. When default_factory is None, defaultdict behaves exactly like a regular dict — it raises KeyError for missing keys. Setting it to None disables the auto-creation behaviour.

This is actually useful when you want a dict that you might later change to have a factory, or when you want to disable the default temporarily.
Q 20 Predict Output Medium
Converting to plain dict
from collections import defaultdict

d = defaultdict(list)
d["a"].append(1)
d["b"].append(2)

plain = dict(d)
plain["c"]   # access missing key on plain dict
Output
KeyError: 'c'
Converting with dict(dd) creates a plain dict. All keys and values are copied. But the auto-creation behaviour is gone — plain["c"] raises KeyError.

Best practice: Return dict(dd) from functions so callers get predictable plain dicts. Keep the defaultdict internal. This prevents callers from accidentally creating keys via reads.
Q 21 Multiple Choice Hard
Factory is called how?
from collections import defaultdict

def my_factory(key="default"):
    return key.upper()

d = defaultdict(my_factory)
print(d["x"])
Answer: b) "DEFAULT". The factory is always called with zero arguments. The missing key is NOT passed to it. my_factory() uses its default arg key="default", so it returns "default".upper() = "DEFAULT".

If you need the key inside the factory, you can't use defaultdict directly. You'd need to subclass dict and override __missing__(self, key).
Q 22 Predict Output Hard
Custom __missing__ — key-aware factory
class SmartDict(dict):
    def __missing__(self, key):
        # Called automatically when key not found
        value = key.upper()
        self[key] = value   # store so it's not recomputed
        return value

d = SmartDict()
print(d["hello"])
print(d["world"])
print(list(d.keys()))
Output
HELLO WORLD ['hello', 'world']
__missing__ is the hook that defaultdict uses internally. By subclassing dict and overriding it, you can create factories that know the missing key. This is the answer to Q21's limitation — when you need the key to compute the default.

defaultdict is just a dict subclass that implements __missing__ to call default_factory(). That's the whole magic — nothing more.
Section 7 — LeetCode Problems using defaultdict
Q 23 LeetCode 49 Medium
Group Anagrams
Given an array of strings, group the anagrams together. Return a list of groups. Two strings are anagrams if they have the same characters (regardless of order).
Example
strs = ["eat","tea","tan","ate","nat","bat"] groupAnagrams(strs) → [["eat","tea","ate"], ["tan","nat"], ["bat"]]
defaultdict(list)sorted() as keytuple as dict key
Solution
from collections import defaultdict

def groupAnagrams(strs):
    # Key insight: anagrams share the same sorted character tuple
    groups = defaultdict(list)
    for s in strs:
        key = tuple(sorted(s))   # "eat" → ('a','e','t')
        groups[key].append(s)
    return list(groups.values())
Key insight: Anagrams produce the same sorted tuple. Use that as the dict key. defaultdict(list) auto-creates the group when a new anagram signature is seen. Without it, you'd need: if key not in groups: groups[key] = [].

Time: O(n · k log k) where k is max string length. Space: O(n · k).
Q 24 LeetCode 347 Medium
Top K Frequent Elements
Given an integer array and an integer k, return the k most frequent elements. Use defaultdict(int) to count, then bucket sort by frequency.
Example
nums = [1,1,1,2,2,3], k = 2 topKFrequent(nums, 2) → [1, 2]
defaultdict(int)defaultdict(list)bucket sort
Solution
from collections import defaultdict

def topKFrequent(nums, k):
    # Step 1: count frequencies
    freq = defaultdict(int)
    for n in nums:
        freq[n] += 1

    # Step 2: bucket sort — index = frequency, value = list of nums
    buckets = defaultdict(list)
    for num, count in freq.items():
        buckets[count].append(num)

    # Step 3: collect top-k from highest freq bucket down
    result = []
    for count in range(len(nums), 0, -1):
        result.extend(buckets[count])
        if len(result) >= k:
            break
    return result[:k]
Two defaultdicts in one solution: defaultdict(int) for counting, defaultdict(list) for bucketing by frequency. Bucket sort gives O(n) time — better than heap-based O(n log k) approaches.

Note: buckets[count] safely returns [] for any count with no numbers — no need to check if count exists.
Q 25 Coding Problem Hard
Frequency of Frequencies
Given a list of words, first count word frequencies. Then count how many words have each frequency. Return a dict of {frequency: count_of_words_with_that_freq}. Use two defaultdict(int)s chained together.
Example
words = ["a","b","a","c","b","a","d"] freq_of_freq(words) → {3: 1, 2: 1, 1: 2} # "a" appears 3 times (1 word with freq 3) # "b" appears 2 times (1 word with freq 2) # "c","d" appear 1 time each (2 words with freq 1)
chained defaultdictfreq of freq.values()
Solution
from collections import defaultdict

def freq_of_freq(words):
    # Step 1: word → its frequency
    word_freq = defaultdict(int)
    for w in words:
        word_freq[w] += 1

    # Step 2: frequency → how many words have it
    fof = defaultdict(int)
    for count in word_freq.values():
        fof[count] += 1

    return dict(fof)
Chain pattern: Use the values of the first defaultdict as the keys of the second. This is a very common two-pass pattern: first count something, then count the counts. Appears in problems like "Find the Celebrity", "Find All Anagrams", and database aggregation.

The elegance of defaultdict(int) is that both passes look identical — just d[key] += 1 — regardless of what kind of key you're counting.
Quick Reference — Pick your factory:

defaultdict(int) → counters, frequencies, prefix sums
defaultdict(list) → grouping, indexing, adjacency lists
defaultdict(set) → unique grouping, deduplication, graph edges
defaultdict(lambda: X) → any custom constant default
defaultdict(lambda: defaultdict(int)) → two-level grouping

3 rules to remember:
1. Reading a missing key creates it — use .get() to peek without side effects
2. For nesting, always use lambda: defaultdict(...) — never pass an instance directly
3. Return dict(dd) from functions — callers get clean, predictable plain dicts
← Category H: Real-world & Pythonic Category J: Live Company Questions →