Shortest Word Chain and Citation H-Index
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement two standalone functions in the same module:
Part 1 — Shortest Single-Letter Word Chain (ladder_length)
Write ladder_length(begin_word, end_word, word_list) -> int to find the fewest words in a valid transformation chain starting at begin_word and ending at end_word:
- Every step replaces one character at a single index while keeping the word length fixed.
- Every word after
begin_word(includingend_worditself) must appear inword_list;begin_worddoes not need to belong toword_list. - Return the number of words in a shortest chain (counting both endpoints).
- If
begin_word == end_word, return1. Ifbegin_wordandend_worddiffer in length, or ifend_wordcannot be reached through valid dictionary steps, return0.
Part 2 — Researcher Citation Metric (h_index)
Write h_index(citations) -> int where citations[i] gives the citation count of publication i. Return the largest integer h for which at least h publications in citations each have at least h citations.
Examples
Example 1
Input: begin_word = "cold", end_word = "warm", word_list = ["cord", "card", "ward", "warm", "carp"]
Output: 5
Explanation: Changing one letter per step produces "cold" -> "cord" -> "card" -> "ward" -> "warm", which contains 5 words (4 single-letter edits), and every intermediate word plus "warm" is in word_list.
Example 2
Input: begin_word = "cold", end_word = "warm", word_list = ["cord", "card", "ward"]
Output: 0
Explanation: Because "warm" is absent from word_list, no legal transformation chain can finish at "warm".
Example 3
Input: citations = [8, 1, 4, 0, 9, 4]
Output: 4
Explanation: Four publications have 4 or more citations (8, 4, 9, and 4), while only two publications reach 5 or more (8 and 9). Thus the maximum valid h is 4.
Constraints
- Part 1:
1 <= len(word_list) <= 5000; words along any valid chain have equal lengthM. Aim forO(N * M^2)character work (O(N * M)pattern transitions) rather thanO(N^2 * M)pairwise word comparisons. - Part 2:
0 <= len(citations) <= 10^5. Aim forO(n)(orO(n log n)) time.
Step-by-step walkthrough
Understand both problems and lock down edge rules
We need to write two independent functions with fast worst-case runtimes:
-
ladder_length(begin_word, end_word, word_list) -> int: Find a shortest transformation chain frombegin_wordtoend_wordchanging one character per step, where every word afterbegin_wordexists inword_list. Importantly, the return value counts the words in the chain (both ends included), not the number of steps:"cold" -> "cord" -> "card" -> "ward" -> "warm"makes 4 single-letter swaps, so it contains 5 words and returns5.- If no valid chain exists (for instance,
end_wordis missing fromword_list), return0. begin_worditself does not need to be inword_list. Ifbegin_word == end_word, a chain of[begin_word]already reaches the target with 1 word, so we return1.
-
h_index(citations) -> int: Given citation counts fornpublications, return the largest integerhsuch that at leasthpublications each have at leasthcitations.- Since an author with
npublications can never have more thannqualifying items,halways lies between0andn.
- Since an author with
from typing import List def ladder_length(begin_word: str, end_word: str, word_list: List[str]) -> int: ... def h_index(citations: List[int]) -> int: ...-
Part 1: Model one-letter swaps as a graph and pick BFS
Think of each word as a node (dot) in a graph, with an undirected edge (line) connecting two words whenever they share the same length and differ at only one character index. A valid word chain is simply a path from
begin_wordtoend_wordin this graph.Because every single-letter swap adds
1to the chain length, all edges have equal cost. On an unweighted graph, breadth-first search (BFS) — an algorithm that explores nodes ring by ring in increasing order of distance from the start — guarantees that the very first time we reachend_word, we have found a shortest chain.Why not depth-first search (DFS), and why not compare every pair of words? - DFS plunges deep down one path first; it might find a 10-word detour before a 3-word shortcut unless it tries every possible path, which takes exponential time. - Pairwise comparison checks all
N * (N - 1) / 2word pairs to build edges. WithN = 5,000words of lengthM, that is about12.5 millionpairs before our search even begins. We need a faster way to find one-letter neighbors.Part 1 key idea: Group neighbors with wildcard buckets
When do two same-length words like
"card"and"ward"differ in only one position? Exactly when blanking out that one position turns both words into the same wildcard template ("*ard").A word of length
MhasMsingle-wildcard patterns — one for each character index:word: "cord" index 0: "*ord" index 1: "c*rd" index 2: "co*d" index 3: "cor*"If we insert every word from
word_listinto a dictionary keyed by itsMwildcard patterns, any two words that differ by one letter automatically land in the same bucket:pattern matching words in ["cord", "card", "ward", "warm", "carp"] ------- ---------------------------------------------------------- "c*rd" -> ["cord", "card"] "*ard" -> ["card", "ward"] "car*" -> ["card", "carp"] "war*" -> ["ward", "warm"] (other patterns like "*ord" or "w*rm" hold just 1 word)Instead of comparing against all
Nwords, looking up a word's neighbors only inspects itsMpattern buckets. Let's write the small helper that builds a word's wildcard patterns:from typing import List def _patterns(word: str) -> List[str]: """Return every single-letter wildcard pattern, e.g. 'cord' -> ['*ord', 'c*rd', 'co*d', 'cor*'].""" patterns: List[str] = [] for index in range(len(word)): prefix = word[:index] suffix = word[index + 1:] patterns.append(prefix + "*" + suffix) return patternsPart 1: Write the BFS and trace Example 1
We run BFS using a first-in, first-out queue (
collections.deque) storing(current_word, chain_length)pairs, starting from(begin_word, 1). Two small implementation details keep the search fast on dense word lists:- Mark words
visitedwhen enqueuing, not when popping. If two words on the same BFS ring both connect to the same neighbor, marking that neighbor visited the first time we enqueue it prevents duplicate copies from piling up in the queue. - Use
buckets.pop(pattern, [])to clear each bucket after scanning it once. The first time any word scans"*ard", every word inbuckets["*ard"]becomes visited and is queued. A later word like"ward"also has pattern"*ard", and re-scanning that bucket could never find a brand-new word — it would only waste time looping over already-visited words (O(N^2)if thousands of words share a bucket). Popping removes the bucket so each entry acrossbucketsis visited at most once.
from typing import Dict, List from collections import deque def ladder_length(begin_word: str, end_word: str, word_list: List[str]) -> int: # Single-letter replacements preserve length, so mismatched lengths can never connect. if len(begin_word) != len(end_word): return 0 if begin_word == end_word: return 1 # A chain of [begin_word] already has 1 word and needs 0 replacements. word_set = set(word_list) if end_word not in word_set: return 0 # Every transformed word, including end_word, must appear in word_list. # Phase 1: Group words by wildcard pattern so one-letter neighbors share a bucket. # buckets: dict mapping pattern -> list of matching words, e.g. {'*ard': ['card', 'ward']} buckets: Dict[str, List[str]] = {} for word in word_set: for pattern in _patterns(word): if pattern not in buckets: buckets[pattern] = [] buckets[pattern].append(word) # Phase 2: Breadth-first search by chain length so the first hit of end_word is shortest. # queue: FIFO deque of (current_word, words_in_chain_so_far), e.g. deque([('cold', 1)]) visited = {begin_word} queue = deque([(begin_word, 1)]) while queue: current_word, chain_length = queue.popleft() for pattern in _patterns(current_word): # Pop the bucket so each pattern list is scanned at most once across the whole BFS; # every word inside it becomes visited right now, preventing O(N^2) re-scans. neighbors = buckets.pop(pattern, []) for neighbor in neighbors: if neighbor == end_word: return chain_length + 1 if neighbor not in visited: # Mark visited on enqueue (not dequeue) so duplicate copies never enter queue. visited.add(neighbor) queue.append((neighbor, chain_length + 1)) return 0Here is how the queue evolves on
begin_word = "cold",end_word = "warm",word_list = ["cord", "card", "ward", "warm", "carp"]:popped item pattern that hits newly found words queue after step ------------ ----------------- ----------------- -------------------------- ("cold", 1) "co*d" "cord" [("cord", 2)] ("cord", 2) "c*rd" "card" [("card", 3)] ("card", 3) "*ard", "car*" "ward", "carp" [("ward", 4), ("carp", 4)] ("ward", 4) "war*" "warm" == end_word! return 4 + 1 = 5- Mark words
Part 2 warm-up: Sort descending and find the cutoff
Before jumping to linear time, let's build intuition for
h_indexby orderingcitationsfrom largest to smallest.Take Example 3:
citations = [8, 1, 4, 0, 9, 4]. Ordered from highest to lowest, that is[9, 8, 4, 4, 1, 0]. At 0-based indexi, we have looked ati + 1publications so far, andordered[i]is the smallest citation count among thosei + 1publications:0-based index i: 0 1 2 3 4 5 paper count (i + 1): 1 2 3 4 5 6 ordered[i] citations: 9 8 4 4 1 0 ordered[i] >= i + 1? yes yes yes yes NO NO ^ last passing rank -> h = 4As
i + 1goes up (1, 2, 3, 4, ...) andordered[i]goes down (9, 8, 4, 4, ...), the testordered[i] >= i + 1holds for a contiguous prefix and then stays false forever. Sorting takesO(n log n)time, which already passesn <= 10^5, and shows clearly why the answer is unique.Part 2 in O(n) time: Cap counts at n and scan downward
Can we avoid the
O(n log n)sort? Notice that if you haven = 6publications in total, a paper with500citations helps no more than a paper with6citations, becausehcan never exceed6.So we can cap every citation count larger than
ndown ton, and tally counts in a bucket listcountsof sizen + 1(indices0..n): -counts[k]stores how many papers have exactlykcitations (for0 <= k < n). -counts[n]stores how many papers havenor more citations.Now walk
candidate_hdownward fromnto0, addingcounts[candidate_h]into a running totalpapers_at_least_h: - At stepcandidate_h,papers_at_least_hequalscounts[n] + counts[n - 1] + ... + counts[candidate_h], which is the exact number of papers with at leastcandidate_hcitations! - Because we walk fromndownward, the very firstcandidate_hwherepapers_at_least_h >= candidate_his guaranteed to be the maximum validh.Let's trace
citations = [8, 1, 4, 0, 9, 4](num_papers = 6): -8 >= 6and9 >= 6both land incounts[6], while1, 4, 0, 4go into their exact slots:slot k: 0 1 2 3 4 5 6+ counts[k]: [1, 1, 0, 0, 2, 0, 2] candidate_h = 6: papers_at_least_h = 0 + 2 = 2 (2 >= 6? No) candidate_h = 5: papers_at_least_h = 2 + 0 = 2 (2 >= 5? No) candidate_h = 4: papers_at_least_h = 2 + 2 = 4 (4 >= 4? Yes -> return 4!)Complete solution
Putting both functions and the wildcard helper together gives the complete
solution.py:from typing import Dict, List from collections import deque def _patterns(word: str) -> List[str]: """Return every single-letter wildcard pattern, e.g. 'cord' -> ['*ord', 'c*rd', 'co*d', 'cor*'].""" patterns: List[str] = [] for index in range(len(word)): prefix = word[:index] suffix = word[index + 1:] patterns.append(prefix + "*" + suffix) return patterns def ladder_length(begin_word: str, end_word: str, word_list: List[str]) -> int: # Single-letter replacements preserve length, so mismatched lengths can never connect. if len(begin_word) != len(end_word): return 0 if begin_word == end_word: return 1 # A chain of [begin_word] already has 1 word and needs 0 replacements. word_set = set(word_list) if end_word not in word_set: return 0 # Every transformed word, including end_word, must appear in word_list. # Phase 1: Group words by wildcard pattern so one-letter neighbors share a bucket. # buckets: dict mapping pattern -> list of matching words, e.g. {'*ard': ['card', 'ward']} buckets: Dict[str, List[str]] = {} for word in word_set: for pattern in _patterns(word): if pattern not in buckets: buckets[pattern] = [] buckets[pattern].append(word) # Phase 2: Breadth-first search by chain length so the first hit of end_word is shortest. # queue: FIFO deque of (current_word, words_in_chain_so_far), e.g. deque([('cold', 1)]) visited = {begin_word} queue = deque([(begin_word, 1)]) while queue: current_word, chain_length = queue.popleft() for pattern in _patterns(current_word): # Pop the bucket so each pattern list is scanned at most once across the whole BFS; # every word inside it becomes visited right now, preventing O(N^2) re-scans. neighbors = buckets.pop(pattern, []) for neighbor in neighbors: if neighbor == end_word: return chain_length + 1 if neighbor not in visited: # Mark visited on enqueue (not dequeue) so duplicate copies never enter queue. visited.add(neighbor) queue.append((neighbor, chain_length + 1)) return 0 def h_index(citations: List[int]) -> int: num_papers = len(citations) # Phase 1: Count papers by citation count, capping any count above num_papers. # counts: list of length (num_papers + 1) where counts[k] = papers with k citations # for k < num_papers, and counts[num_papers] = papers with >= num_papers citations. counts = [0] * (num_papers + 1) for cite_count in citations: if cite_count >= num_papers: counts[num_papers] += 1 elif cite_count >= 0: # Guard cite_count >= 0 so negative inputs cannot wrap around via counts[-1]. counts[cite_count] += 1 # Phase 2: Sweep candidate h from largest (num_papers) down to 0. # Because we go top-down, the first h with at least h qualifying papers is the maximum. papers_at_least_h = 0 for candidate_h in range(num_papers, -1, -1): papers_at_least_h += counts[candidate_h] if papers_at_least_h >= candidate_h: return candidate_h return 0✅ Submit now — all tests should pass.
Intuition & how it works
Each part becomes fast once we pick the right index structure instead of re-scanning raw items:
- Part 1 (Word Chain): Imagine stepping across lily pads in a pond where you can hop between two words only if they differ by a single letter. To find the fewest hops, we use breadth-first search (BFS) — a graph traversal that explores nodes level by level in order of distance from the start — combined with wildcard buckets (templates with one * blank, such as "*ard" for "card" and "ward") that act like a phonebook of one-letter neighbors.
- Part 2 (H-Index): Imagine lining up an author's n publications as vertical bars sorted from tallest citation count to shortest, and sliding a k x k square up until it stops fitting under the bars. Because that square can never be wider than n (the total number of publications), we use bucket counting — tallying how many publications fall into each count 0, 1, ..., n-1, plus one catch-all bucket n+ for everything >= n — and add those tallies from n downward.
Why do the naive approaches fall short? In Part 1, exploring depth-first can return a long winding detour instead of a shortest path, and building edges by comparing every pair of words takes N * (N - 1) / 2 comparisons (over 12 million word pairs when N = 5,000). In Part 2, testing each candidate h by scanning the whole array takes O(n^2) time (10 billion checks when n = 10^5), while even an O(n log n) sort spends extra work ordering huge numbers like 500 and 9,000 that behave identically on a 6-paper list.
Here is a tiny end-to-end trace of both ideas on our examples:
- Word Chain on begin = "cold", end = "warm", word_list = ["cord", "card", "ward", "warm", "carp"]:
1. Index wildcard buckets: "co*d": ["cord"], "c*rd": ["cord", "card"], "*ard": ["card", "ward"], "car*": ["card", "carp"], "war*": ["ward", "warm"] (plus single-word buckets).
2. Queue starts with ("cold", 1). Popping "cold" checks "co*d" -> pops ["cord"] -> enqueue ("cord", 2).
3. Popping ("cord", 2) checks "c*rd" -> pops ["cord", "card"] -> enqueue unvisited ("card", 3).
4. Popping ("card", 3) checks "*ard" and "car*" -> enqueue ("ward", 4) and ("carp", 4).
5. Popping ("ward", 4) checks "war*" -> sees "warm" == end, returning 4 + 1 = 5 words ("cold" -> "cord" -> "card" -> "ward" -> "warm").
- H-Index on citations = [8, 1, 4, 0, 9, 4] (n = 6):
1. Cap counts above 6 at 6, filling counts[0..6] = [1, 1, 0, 0, 2, 0, 2].
2. Sweep downward: at h = 6, 2 items have >= 6 (2 < 6); at h = 5, still 2 items (2 < 5); at h = 4, 2 + 2 = 4 items have >= 4 (4 >= 4), so we immediately return 4.
Complexity
Let N be the number of words in word_list, M be the length of each word, and n be the length of citations.
- Word Chain time —
O(N * M^2)character operations (often writtenO(N * M)treating short fixed-length string slicing asO(1)): For each of the at mostNunique words (plusbegin_word), we buildMwildcard strings, and slicing/hashing one length-Mstring readsMcharacters (M * M = M^2work per word). Becausebuckets.pop(pattern, [])deletes each bucket the first time it is scanned, the inner neighbor loop runs at mostN * Mtimes in total across the entire BFS. - Word Chain space —
O(N * M^2): There are up toN * M(pattern, word)references inbuckets, and up toN * Mdistinct pattern strings of lengthMeach (N * M^2characters total), whilevisitedandqueuestore at mostN + 1words. - H-Index time —
O(n): We scan thencitation counts once to populatecounts, and then stepcandidate_hdown through at mostn + 1buckets, doingO(1)arithmetic at each step. (The sorting alternative takesO(n log n)time to sortnintegers.) - H-Index space —
O(n): We allocate a single listcountsofn + 1integers regardless of how large individual citation numbers are.
Edge cases
end_wordmissing fromword_list: Even ifend_worddiffers frombegin_wordby one letter (for example"cold"to"cord"withword_list = []), the target must belong toword_list, so we return0immediately.begin_wordmissing fromword_list: Allowed — only transformed words afterbegin_wordmust belong toword_list.begin_word == end_word: Returns1(a 1-word chain requires zero swaps); state this assumption out loud in an interview, as many variants guaranteebegin_word != end_word.- Mismatched lengths or duplicate words in
word_list: Checkinglen(begin_word) != len(end_word)handles length mismatches up front, and convertingword_listtoset(word_list)strips duplicates so buckets hold no repeated neighbors. - Empty
citationsor all-zerocitations([]or[0, 0, 0]): The downward sweep reachescandidate_h = 0wherepapers_at_least_h >= 0holds, returning0. - Citation counts much larger than
n(e.g.,[100]): Capped intocounts[1], givingpapers_at_least_h = 1 >= 1and returning1without allocating a 101-element array. - Negative numbers in untrusted input: Guarding
elif cite_count >= 0ensures a bad value like-1is ignored rather than indexingcounts[-1](which Python interprets as the last bucketcounts[n]).
Common mistakes
- Returning edge count instead of word count in Part 1: Returning
4instead of5on"cold" -> "cord" -> "card" -> "ward" -> "warm"is an off-by-one error; initialize the queue with(begin_word, 1), not(begin_word, 0). - Marking words
visitedon dequeue instead of enqueue: If ten words on level 2 all connect to"ward", waiting until"ward"is popped lets ten copies of"ward"enter the queue, bloating both memory and runtime. - Leaving scanned wildcard buckets in
buckets: Withoutbuckets.pop(pattern, []), ifKwords all share a pattern like"*aa", each of thoseKwords loops over allKentries again, degrading toO(K^2)(O(N^2)worst case). - Hardcoding
'a'..'z'character replacements without asking: Trying 26 letters per position assumes lowercase ASCII letters; wildcard buckets work identically for uppercase, digits, or Unicode characters. - Sizing
countsbymax(citations)instead oflen(citations): A single paper with10^9citations would crash withMemoryErrorif not capped atn. - Off-by-one in the sorted H-index check: With 0-based index
i, there arei + 1papers up toi, so the condition isordered[i] >= i + 1(notordered[i] >= i).
Follow-up questions
- How can you speed up the word-chain search when the dictionary scales to several million entries? Use bidirectional BFS — running two breadth-first searches simultaneously, one forward from
begin_wordand one backward fromend_word, always expanding whichever frontier currently holds fewer words until the two frontiers meet. If each word branches tob = 10new words and the shortest path hasd = 6steps, one-sided BFS explores roughly10^6 = 1,000,000nodes, whereas two-sided BFS explores roughly2 * 10^3 = 2,000nodes. For millions of words, the wildcard dictionary (N * Mstrings) can also consume gigabytes of RAM; if memory is tight, dropbuckets, store onlyword_set, and generate the25 * Mone-letter lowercase candidates on the fly inO(N * M)space, or precompute connected components with union-find (a disjoint-set structure that tracks which nodes can reach one another in near-O(1)time) if serving many queries against a static dictionary. - How would you compute the H-index over a massive stream of citation counts that cannot fit in RAM? Notice that as publications arrive one by one,
hcan never decrease and grows by at most1per item. Maintainhalongside a min-heap — a binary tree priority queue that keeps its smallest value at the root inO(log k)time per push/pop — holding only citation counts strictly greater thanh: wheneverlen(above) > h, at leasth + 1seen items have>= h + 1citations, so incrementhby1and pop all heap roots<= h. This runs in a single pass usingO(h)RAM (just megabytes whenh <= 10^6, even ifn = 10^10). If an adversarial stream could makehitself billions and disk re-reads are allowed, use a two-pass bucketed histogram (2^208-byte counters = 8 MiB: pass 1 counts ranges of width2^20to locate the exact range containingh, and pass 2 counts exact values inside that single range) or binary-searchhinO(log n)passes withO(1)RAM.
import heapq
def streaming_h_index(stream):
h = 0
above = [] # min-heap of seen citation counts strictly greater than h
for cite_count in stream:
if cite_count > h:
heapq.heappush(above, cite_count)
if len(above) > h:
h += 1
while above and above[0] <= h:
heapq.heappop(above)
return h
- When the one-letter transition graph is very dense, how do different search strategies compare in peak memory footprint? In a dense word graph, most words sit only 2 or 3 steps from
begin_word, so standard BFS quickly pulls a huge fraction of allNwords into bothvisitedandqueue, requiringO(N)node memory (plusO(N * M^2)if you build the wildcard index, which is still up to 25 times smaller than storing an explicit adjacency list of all neighbor pairs). Standard DFS with avisitedset still usesO(N)memory AND fails to guarantee a shortest path. Iterative deepening DFS — running depth-limited DFS without a globalvisitedset for depth limits1, 2, 3, ...— drops traversal memory toO(depth)words on the call stack, at the cost of re-visiting the same words across many paths (O(branching^depth)time, prohibitive on dense graphs). In practice, bidirectional BFS overword_set(generating single-letter variants on the fly without storingbuckets) gives the best balance, keeping both frontiers tiny until they meet in the middle.
Follow-up questions
- How can you speed up the word-chain search when the dictionary scales to several million entries?
- How would you compute the H-index over a massive stream of citation counts that cannot fit in RAM?
- When the one-letter transition graph is very dense, how do different search strategies compare in peak memory footprint?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array