Bird
Raised Fist0
Interview Prepgraphs-dfs-bfshardAmazonFacebookGoogleBloomberg

Word Ladder

Choose your preparation mode4 modes available
📋
Problem

Imagine you want to transform one word into another by changing one letter at a time, like a puzzle where each step must be a valid English word. How quickly can you find the shortest transformation?

Given two words, beginWord and endWord, and a dictionary wordList, find the length of the shortest transformation sequence from beginWord to endWord such that: 1. Only one letter can be changed at a time. 2. Each transformed word must exist in the wordList. Return 0 if no such sequence exists. Input: beginWord (string), endWord (string), wordList (list of strings) Output: integer representing the length of the shortest transformation sequence.

1 ≤ length of beginWord, endWord ≤ 101 ≤ number of words in wordList ≤ 10^5All words have the same lengthAll words contain only lowercase English letters
Edge cases: endWord not in wordList → 0beginWord equals endWord → 1wordList empty → 0
</>
IDE
def word_ladder_bruteforce(beginWord: str, endWord: str, wordList: list) -> int:public int wordLadderBruteforce(String beginWord, String endWord, List<String> wordList)int wordLadderBruteforce(string beginWord, string endWord, vector<string> wordList)function wordLadderBruteforce(beginWord, endWord, wordList)
def word_ladder_bruteforce(beginWord, endWord, wordList):
    # Write your solution here
    pass
class Solution {
    public int wordLadderBruteforce(String beginWord, String endWord, List<String> wordList) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int wordLadderBruteforce(string beginWord, string endWord, vector<string> wordList) {
    // Write your solution here
    return 0;
}
function wordLadderBruteforce(beginWord, endWord, wordList) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Not checking if beginWord equals endWord, returning 0 instead of 1.✅ Add condition: if beginWord == endWord: return 1
Wrong: non-zero (e.g. 1 or 2) when no path existsNot verifying endWord presence in wordList before BFS or incorrect BFS termination.✅ Return 0 if endWord not in wordList before BFS starts.
Wrong: Longer path length or incorrect pathUsing greedy or DFS instead of BFS, missing shortest path guarantee.✅ Implement BFS with queue and visited set to find shortest path.
Wrong: Infinite loop or repeated nodes causing wrong outputMissing visited set causing revisiting nodes multiple times.✅ Maintain visited set to mark words already processed in BFS.
Wrong: TLE or timeoutUsing brute force DFS or inefficient neighbor generation on large inputs.✅ Use BFS with efficient neighbor generation and pruning; avoid DFS on large inputs.
✓
Test Cases
t1_01basic
Input{"beginWord":"hit","endWord":"cog","wordList":["hot","dot","dog","lot","log","cog"]}
Expected5

One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", length 5.

t1_02basic
Input{"beginWord":"game","endWord":"thee","wordList":["fame","fate","gate","gape","tape","tame","thee"]}
Expected0

No valid transformation sequence from "game" to "thee" exists with one letter changes only.

t2_01edge
Input{"beginWord":"same","endWord":"same","wordList":["same"]}
Expected1

BeginWord equals endWord, so shortest transformation length is 1 (no changes needed).

t2_02edge
Input{"beginWord":"hit","endWord":"cog","wordList":[]}
Expected0

Empty wordList means no transformations possible; return 0.

t2_03edge
Input{"beginWord":"hit","endWord":"hot","wordList":["hot"]}
Expected2

One letter difference between beginWord and endWord, and endWord in wordList; shortest path length is 2.

t3_01corner
Input{"beginWord":"aaa","endWord":"bbb","wordList":["aab","abb","bbb"]}
Expected4

Shortest path is "aaa" -> "aab" -> "abb" -> "bbb", length 4. Tests BFS correctness over greedy approach.

t3_02corner
Input{"beginWord":"abc","endWord":"xyz","wordList":["xbc","xyc","xyz"]}
Expected4

Tests confusion between 0/1 knapsack style unbounded vs 0/1 BFS: each word can be used once only, path length 4.

t3_03corner
Input{"beginWord":"hit","endWord":"cog","wordList":["hot","dot","dog","lot","log"]}
Expected0

endWord "cog" not in wordList, so no transformation possible; return 0.

t4_01performance
Input{"beginWord":"aaaaa","endWord":"zzzzz","wordList":["aaaaa","aaaab","aaabb","aabbb","abbbb","bbbbb","bbbbc","bbbcc","bbccc","bcccc","ccccc","ccccd","ccddd","cdddd","ddddd","ddddz","dddzz","ddzzz","dzzzz","zzzzz","aaaac","aaacc","aaccc","acccc","ccccc","ccccd","ccddd","cdddd","ddddd","ddddd","zzzzz","zzzza","zzzaz","zzazz","zazzz","azzzz"]}
⏱ Performance - must finish in 2000ms

Large input with n=40 words, word length=5, BFS O(n*L*26) must complete within 2s.

Practice

(1/5)
1. You are given a graph with n nodes and n-1 edges, where exactly one node is connected to all other nodes, forming a star shape. Which approach guarantees finding the center node in O(n) time without unnecessary graph traversal?
easy
A. Count the frequency of each node in the edges and return the node appearing n-1 times.
B. Apply dynamic programming to store intermediate results of node degrees and find the maximum.
C. Use a greedy approach by picking the first node in the first edge as the center without verification.
D. Perform a depth-first search (DFS) from each node to count its neighbors and identify the center.

Solution

  1. Step 1: Understand the star graph property

    In a star graph with n nodes, the center node appears in every edge, so it has degree n-1.
  2. Step 2: Use frequency counting

    Counting how many times each node appears in the edges lets us find the node with degree n-1 efficiently in O(n) time.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Frequency counting directly identifies the center without traversal [OK]
Hint: Center node appears in all edges [OK]
Common Mistakes:
  • Assuming the first node in edges is always center
  • Using DFS from every node causing O(n²) time
  • Applying DP unnecessarily for a simple counting problem
2. You are given an undirected graph and need to determine if its vertices can be divided into two groups such that no edge connects vertices within the same group. Which algorithmic approach guarantees an efficient and correct solution for this problem?
easy
A. Greedy algorithm that assigns groups based on vertex degree
B. Dynamic Programming on subsets of vertices to find valid partitions
C. Depth-First Search (DFS) to find cycles and count their lengths
D. Breadth-First Search (BFS) coloring to assign two colors and check for conflicts

Solution

  1. Step 1: Understand the problem as a 2-coloring challenge

    The problem requires checking if the graph is bipartite, which means it can be colored using two colors such that no adjacent vertices share the same color.
  2. Step 2: Identify BFS coloring as the optimal approach

    BFS coloring systematically assigns colors level by level and detects conflicts efficiently, guaranteeing correctness and linear time complexity.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    BFS coloring is the standard method for bipartite checking [OK]
Hint: BFS coloring detects bipartite conflicts efficiently [OK]
Common Mistakes:
  • Assuming greedy degree-based grouping works
  • Confusing cycle detection with bipartite check
3. The following code attempts to check if a graph is a valid tree. Which line contains a subtle bug that can cause incorrect results on disconnected graphs?
medium
A. Line checking if edge count equals n - 1
B. Line returning true without verifying all nodes visited
C. Line skipping neighbor if it equals parent
D. Line adding neighbor to queue

Solution

  1. Step 1: Identify final return condition

    The code returns true without checking if all nodes were visited, missing disconnected components.
  2. Step 2: Understand impact

    Disconnected graphs with correct edge count and no cycles will incorrectly return true.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Must verify visited nodes count equals n [OK]
Hint: Always check all nodes visited for connectivity [OK]
Common Mistakes:
  • Forgetting connectivity check after BFS/DFS
  • Misinterpreting cycle detection as full validation
4. The following BFS code attempts to find the max area of an island in a grid. Identify the line that contains a subtle bug that can cause incorrect area calculation or runtime errors.
from collections import deque

def maxAreaOfIsland(grid):
    rows, cols = len(grid), len(grid[0])
    visited = set()
    max_area = 0

    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 1 and (r, c) not in visited:
                queue = deque([(r, c)])
                area = 0
                while queue:
                    row, col = queue.popleft()
                    # Bug: Missing visited check here
                    visited.add((row, col))
                    area += 1
                    for nr, nc in [(row+1,col),(row-1,col),(row,col+1),(row,col-1)]:
                        if grid[nr][nc] == 1 and (nr, nc) not in visited:
                            queue.append((nr, nc))
                max_area = max(max_area, area)
    return max_area
medium
A. Line that adds neighbors to the queue without boundary checks
B. Line that adds (row, col) to visited without checking if already visited
C. Line that initializes the queue with the starting cell
D. Line that updates max_area after BFS completes

Solution

  1. Step 1: Check neighbor addition line

    The code adds neighbors without verifying if nr, nc are within grid boundaries, risking index out of range errors.
  2. Step 2: Confirm other lines are correct

    Visited check before adding to queue is present, queue initialization and max_area update are correct.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Boundary checks missing cause runtime errors [OK]
Hint: Always check grid boundaries before accessing neighbors [OK]
Common Mistakes:
  • Forgetting boundary checks
  • Not checking visited before adding to queue
  • Adding visited check after popping queue
5. What is the worst-case space complexity of the in-place DFS solution for the Number of Islands problem on an m x n grid, considering the recursion stack usage?
medium
A. O(1) -- since the grid is modified in-place, no extra space is needed.
B. O(min(m, n)) -- recursion depth limited by smaller grid dimension.
C. O(m*n) -- recursion stack can grow up to the size of the entire grid in worst case.
D. O(m + n) -- recursion stack limited by sum of rows and columns.

Solution

  1. Step 1: Identify auxiliary space usage

    The grid is modified in-place, so no extra data structures are used except recursion stack.
  2. Step 2: Analyze recursion stack depth

    In worst case (e.g., one large island), DFS can recurse over all cells, leading to recursion stack depth O(m*n).
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Recursion stack can be as large as all grid cells in worst case [OK]
Hint: Recursion stack can be as large as island size [OK]
Common Mistakes:
  • Assuming constant space due to in-place modification
  • Confusing recursion depth with grid dimensions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard