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 (including end_word itself) must appear in word_list; begin_word does not need to belong to word_list.
  • Return the number of words in a shortest chain (counting both endpoints).
  • If begin_word == end_word, return 1. If begin_word and end_word differ in length, or if end_word cannot be reached through valid dictionary steps, return 0.

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 length M. Aim for O(N * M^2) character work (O(N * M) pattern transitions) rather than O(N^2 * M) pairwise word comparisons.
  • Part 2: 0 <= len(citations) <= 10^5. Aim for O(n) (or O(n log n)) time.

Step-by-step walkthrough

  1. Understand both problems and lock down edge rules

    We need to write two independent functions with fast worst-case runtimes:

    1. ladder_length(begin_word, end_word, word_list) -> int: Find a shortest transformation chain from begin_word to end_word changing one character per step, where every word after begin_word exists in word_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 returns 5.
      • If no valid chain exists (for instance, end_word is missing from word_list), return 0.
      • begin_word itself does not need to be in word_list. If begin_word == end_word, a chain of [begin_word] already reaches the target with 1 word, so we return 1.
    2. h_index(citations) -> int: Given citation counts for n publications, return the largest integer h such that at least h publications each have at least h citations.

      • Since an author with n publications can never have more than n qualifying items, h always lies between 0 and n.
    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:
        ...
    
  2. 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_word to end_word in this graph.

    Because every single-letter swap adds 1 to 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 reach end_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) / 2 word pairs to build edges. With N = 5,000 words of length M, that is about 12.5 million pairs before our search even begins. We need a faster way to find one-letter neighbors.

  3. 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 M has M single-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_list into a dictionary keyed by its M wildcard 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 N words, looking up a word's neighbors only inspects its M pattern 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 patterns
    
  4. Part 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:

    1. Mark words visited when 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.
    2. Use buckets.pop(pattern, []) to clear each bucket after scanning it once. The first time any word scans "*ard", every word in buckets["*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 across buckets is 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 0
    

    Here 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
    
  5. Part 2 warm-up: Sort descending and find the cutoff

    Before jumping to linear time, let's build intuition for h_index by ordering citations from 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 index i, we have looked at i + 1 publications so far, and ordered[i] is the smallest citation count among those i + 1 publications:

    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 = 4
    

    As i + 1 goes up (1, 2, 3, 4, ...) and ordered[i] goes down (9, 8, 4, 4, ...), the test ordered[i] >= i + 1 holds for a contiguous prefix and then stays false forever. Sorting takes O(n log n) time, which already passes n <= 10^5, and shows clearly why the answer is unique.

  6. 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 have n = 6 publications in total, a paper with 500 citations helps no more than a paper with 6 citations, because h can never exceed 6.

    So we can cap every citation count larger than n down to n, and tally counts in a bucket list counts of size n + 1 (indices 0..n): - counts[k] stores how many papers have exactly k citations (for 0 <= k < n). - counts[n] stores how many papers have n or more citations.

    Now walk candidate_h downward from n to 0, adding counts[candidate_h] into a running total papers_at_least_h: - At step candidate_h, papers_at_least_h equals counts[n] + counts[n - 1] + ... + counts[candidate_h], which is the exact number of papers with at least candidate_h citations! - Because we walk from n downward, the very first candidate_h where papers_at_least_h >= candidate_h is guaranteed to be the maximum valid h.

    Let's trace citations = [8, 1, 4, 0, 9, 4] (num_papers = 6): - 8 >= 6 and 9 >= 6 both land in counts[6], while 1, 4, 0, 4 go 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!)
    
  7. 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 written O(N * M) treating short fixed-length string slicing as O(1)): For each of the at most N unique words (plus begin_word), we build M wildcard strings, and slicing/hashing one length-M string reads M characters (M * M = M^2 work per word). Because buckets.pop(pattern, []) deletes each bucket the first time it is scanned, the inner neighbor loop runs at most N * M times in total across the entire BFS.
  • Word Chain space — O(N * M^2): There are up to N * M (pattern, word) references in buckets, and up to N * M distinct pattern strings of length M each (N * M^2 characters total), while visited and queue store at most N + 1 words.
  • H-Index time — O(n): We scan the n citation counts once to populate counts, and then step candidate_h down through at most n + 1 buckets, doing O(1) arithmetic at each step. (The sorting alternative takes O(n log n) time to sort n integers.)
  • H-Index space — O(n): We allocate a single list counts of n + 1 integers regardless of how large individual citation numbers are.

Edge cases

  • end_word missing from word_list: Even if end_word differs from begin_word by one letter (for example "cold" to "cord" with word_list = []), the target must belong to word_list, so we return 0 immediately.
  • begin_word missing from word_list: Allowed — only transformed words after begin_word must belong to word_list.
  • begin_word == end_word: Returns 1 (a 1-word chain requires zero swaps); state this assumption out loud in an interview, as many variants guarantee begin_word != end_word.
  • Mismatched lengths or duplicate words in word_list: Checking len(begin_word) != len(end_word) handles length mismatches up front, and converting word_list to set(word_list) strips duplicates so buckets hold no repeated neighbors.
  • Empty citations or all-zero citations ([] or [0, 0, 0]): The downward sweep reaches candidate_h = 0 where papers_at_least_h >= 0 holds, returning 0.
  • Citation counts much larger than n (e.g., [100]): Capped into counts[1], giving papers_at_least_h = 1 >= 1 and returning 1 without allocating a 101-element array.
  • Negative numbers in untrusted input: Guarding elif cite_count >= 0 ensures a bad value like -1 is ignored rather than indexing counts[-1] (which Python interprets as the last bucket counts[n]).

Common mistakes

  • Returning edge count instead of word count in Part 1: Returning 4 instead of 5 on "cold" -> "cord" -> "card" -> "ward" -> "warm" is an off-by-one error; initialize the queue with (begin_word, 1), not (begin_word, 0).
  • Marking words visited on 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: Without buckets.pop(pattern, []), if K words all share a pattern like "*aa", each of those K words loops over all K entries again, degrading to O(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 counts by max(citations) instead of len(citations): A single paper with 10^9 citations would crash with MemoryError if not capped at n.
  • Off-by-one in the sorted H-index check: With 0-based index i, there are i + 1 papers up to i, so the condition is ordered[i] >= i + 1 (not ordered[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_word and one backward from end_word, always expanding whichever frontier currently holds fewer words until the two frontiers meet. If each word branches to b = 10 new words and the shortest path has d = 6 steps, one-sided BFS explores roughly 10^6 = 1,000,000 nodes, whereas two-sided BFS explores roughly 2 * 10^3 = 2,000 nodes. For millions of words, the wildcard dictionary (N * M strings) can also consume gigabytes of RAM; if memory is tight, drop buckets, store only word_set, and generate the 25 * M one-letter lowercase candidates on the fly in O(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, h can never decrease and grows by at most 1 per item. Maintain h alongside a min-heap — a binary tree priority queue that keeps its smallest value at the root in O(log k) time per push/pop — holding only citation counts strictly greater than h: whenever len(above) > h, at least h + 1 seen items have >= h + 1 citations, so increment h by 1 and pop all heap roots <= h. This runs in a single pass using O(h) RAM (just megabytes when h <= 10^6, even if n = 10^10). If an adversarial stream could make h itself billions and disk re-reads are allowed, use a two-pass bucketed histogram (2^20 8-byte counters = 8 MiB: pass 1 counts ranges of width 2^20 to locate the exact range containing h, and pass 2 counts exact values inside that single range) or binary-search h in O(log n) passes with O(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 all N words into both visited and queue, requiring O(N) node memory (plus O(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 a visited set still uses O(N) memory AND fails to guarantee a shortest path. Iterative deepening DFS — running depth-limited DFS without a global visited set for depth limits 1, 2, 3, ... — drops traversal memory to O(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 over word_set (generating single-letter variants on the fly without storing buckets) gives the best balance, keeping both frontiers tiny until they meet in the middle.

Follow-up questions

Similar questions

More Art Advisors interview questions

All 1 Art Advisors questions →