# Edit distance | Word Ladder coding question

Aced (formerly Exponent) publishes a public search API over its indexed pages; the guide is at https://www.aced.io/agents/agent-access.

Source: https://www.aced.io/questions/3891/edit-distance
Source observed: 2026-11-04T21:34:58.496Z
Last checked: 2026-11-04T21:34:58.496+00:00
Indexed: 2026-11-05T00:36:01.465+00:00

---

# Edit distance

We provide this hard Data Structures & Algorithms question through Aced, formerly Exponent. The task asks you to find the minimum number of one-letter changes needed to transform `beginWord` into `endWord`, while requiring every intermediate word to exist in a supplied dictionary.

## Question

**Difficulty:** Hard  
**Category:** Data Structures & Algorithms; Coding  
**Reported interviews:** 13 interviews  
**Reported last asked:** 4 months ago  
**Saved by members:** 199  
**Community:** 81

The page provides tabs for **Question**, **Solution**, **Mock Interview**, and **Community**. The solution and mock-interview tabs are member-locked in the supplied view.

## Problem statement

Determine the Edit Distance in a Word Ladder. Given two words, `beginWord` and `endWord`, and a dictionary word list, return the minimum number of operations needed to change `beginWord` into `endWord`.

You may change only one letter at a time, and every intermediate word must exist in the word list. If no transformation is possible, return:

- `None` in Python
- `-1` in Java and C++
- `null` in JavaScript

## Examples

```text
beginWord = 'hit'
endWord = 'cog'
wordList = ["hit", "hot", "dot", "dog", "cog"]
output: 4
# hit -> hot -> dot -> dog -> cog

beginWord = 'word'
endWord = 'word'
wordList = ['word', 'ward']
output: 0

beginWord = 'hit'
endWord = 'cog'
wordList = ["hit", "hot", "dot", "dog"]
output: None
# because no 'cog' in list
```

## Community code answers

The page includes community-submitted code. These are member answers, not an official solution.

### Ravi kiran V. — Python

[Profile](https://www.aced.io/users/5b964a3e-d16a-4124-9f39-2f3c7171c080) · September 28, 2026 · 366 karma

```python
from collections import deque
def update_word(words, start_word, end_word):
    wordSet = set(words)
    # If the target word isn't in the dictionary, transformation is impossible
    if end_word not in wordSet or start_word not in wordSet:
        return
    # Queue stores tuples of (current_word, number_of_operations)
    queue = deque([(start_word, 0)])
    visited = {start_word}
    while queue:
        current_word, ops = queue.popleft()
        # If we reached the end word, return the operation count
        if current_word == end_word:
            return ops
        # Try changing each character from 'a' to 'z'
        for i in range(len(current_word)):
            for char_code in range(ord('a'), ord('z') + 1):
                c = chr(char_code)
                next_word = current_word[:i] + c + current_word[i + 1:]
                # If the generated word is valid and hasn't been visited yet
                if next_word in wordSet and next_word not in visited:
                    visited.add(next_word)
                    queue.append((next_word, ops + 1))
    return

# debug your code below
beginWord = 'hit'
endWord = 'cog'
wordList = ["hit", "hot", "dot", "dog", "cog"]
print(update_word(wordList, beginWord, endWord))
```

### Sihan A. — Python

[Profile](https://www.aced.io/users/8a90dc59-6dd5-4cf3-b836-0b1988f74890) · August 22, 2026 · 582 karma

```python
import collections
def update_word(words, start_word, end_word):
    # 1. edge cases
    if start_word not in words or end_word not in words:
        return None
    if start_word == end_word:
        return 0
    # 2. build patterns
    patterns = collections.defaultdict(list)
    # pattern: [w1, w2, w3]
    for w in words:
        for i, ch in enumerate(w):
            pattern = w[:i] + "*" + w[i+1:]
            patterns[pattern].append(w)
    # 3. init vars: queue, step, visited
    step = 0
    queue = collections.deque([start_word])
    visited = set()
    visited.add(start_word)
    # 4. run on queue, go to the next word with same pattern, until we find the end word
    while queue:
        size = len(queue)
        for _ in range(size):
            cur = queue.popleft()
            if cur == end_word:
                return step
            for i, ch in enumerate(cur):
                p = cur[:i] + "*" + cur[i+1:]
                for nxt in patterns[p]:
                    if nxt not in visited:
                        queue.append(nxt)
                        visited.add(nxt)
        step += 1
    # 5. return step
    return -1

# debug your code below
beginWord = 'hit'
endWord = 'cog'
wordList = ["hit", "hot", "dot", "dog", "cog"]
print(update_word(wordList, beginWord, endWord))
```

### Kadidjatou Y. — Python

[Profile](https://www.aced.io/users/4b0d1971-5416-4494-8985-ea14289dc139) · October 17, 2026 · 45 karma

```python
def update_word(words, start_word, end_word):
    count = 0
    if end_word not in words or start_word not in words:
        return None
    if end_word==start_word:
        return 0
    for n in range (len(words)):
        if words[n]== start_word:
            count = count
        else :
            count +=1
    return count

# debug your code below
beginWord = 'hit'
endWord = 'cog'
wordList = ["hit", "hot", "dot", "dog", "cog"]
print(update_word(wordList, beginWord, endWord))
```

### Jayraj M. — C++

[Profile](https://www.aced.io/users/8958e211-5406-4c90-aa0e-3547fade5ca4) · September 24, 2026 · 171 karma

```cpp
#include <iostream>
#include <string>
#include <vector>
// #include <bits/stdc++.h>
using namespace std;

int updateWord(const std::vector<std::string>& words, const std::string& startWord, const std::string& endWord) {
    if(startWord == endWord) return 0;
    // words.push_back(endWord);
    // sort(words.begin(),words.end());
    int ans = 0;
    bool cor = false;
    for(auto x:words){
        if(x == startWord) cor = true;
        if(x == endWord && cor) return ans;
        ans++;
    }
    return -1;
}

// comment out main() before running tests
int main() {
    std::vector<std::string> wordList = {"hit", "hot", "dot", "dog", "cog"};
    std::string beginWord = "hit";
    std::string endWord = "cog";
    std::cout << updateWord(wordList, beginWord, endWord) << std::endl;
    // Output: 4
    return 0;
}
```

### Sihan A. — Python

[Profile](https://www.aced.io/users/8a90dc59-6dd5-4cf3-b836-0b1988f74890) · August 11, 2026 · 582 karma

```python
from collections import defaultdict, deque
def update_word(words, start_word, end_word):
    # edge cases
    if end_word not in words or start_word not in words:
        return None
    if start_word == end_word:
        return 0
    # build the graph
    patterns = defaultdict(list)
    for word in words:
        for i in range(len(word)):
            pattern = word[:i] + "*" + word[i + 1:]
            patterns[pattern].append(word)
    # init visited = {start_word}
    visited = {start_word}
    q = deque([start_word])
    steps = 0
    # run the BFS
    while q:
        for _ in range(len(q)):
            cur = q.popleft()
            if cur == end_word:
                return steps
            for i in range(len(cur)):
                pattern = cur[:i] + "*" + cur[i + 1:]
                for nxt in patterns[pattern]:
                    if nxt not in visited:
                        visited.add(nxt)
                        q.append(nxt)
        steps += 1
    return None

# debug your code below
beginWord = 'hit'
endWord = 'cog'
wordList = ["hit", "hot", "dot", "dog", "cog"]
print(update_word(wordList, beginWord, endWord))
```

## Interview experiences

**6 shared** experiences are listed for this question:

- [MongoDB — Software Engineer · Mid Level / L4](https://www.aced.io/experiences/mongodb-software-engineer-interview-bcaba8): Good coding round and overall experience; supportive interviewer; process lasted two months.
- [Meta — Data Scientist · Mid Level / L4](https://www.aced.io/experiences/meta-facebook-data-scientist-interview-7255ae): Casual and easy, with standard questions and many follow-ups.
- [Reddit — Software Engineer · Entry Level / L3](https://www.aced.io/experiences/reddit-software-engineer-interview-6fcd03): Smooth and relatively easy; interviewer was helpful.
- [Amazon — Software Engineer · Mid Level / L4](https://www.aced.io/experiences/amazon-software-engineer-interview-f0007e): Strong DSA preparation and predictable leadership-principle questions.
- [Visa — Software Engineer · Entry Level / L3](https://www.aced.io/experiences/visa-software-engineer-interview-9e2ca9): Resume-based questions, basic object-oriented programming and operating-system concepts, and DSA.
- [Google — Software Engineer · Entry Level / L3](https://www.aced.io/experiences/google-software-engineer-interview-965bee): Data structures, algorithms, and problem-solving; the contributor wanted to manage optimization time better.

## Related courses

![Machine Learning Engineer Interview Prep](https://images.ctfassets.net/x78yjrjc11pq/6UfkHxUyLQVfDHSfLNQtWa/1be1539a65b4f6f15201f5b573c0a578/ML_Engineer_Interview_Prep_Course.jpeg?w=800&h=800&fm=webp&q=75)

### [Machine Learning Engineer Interview Prep](https://www.aced.io/courses/ml-engineer)

We cover ML system design, core concepts, coding, behavioral interviews, mock interviews, frameworks, and advice from senior candidates for roles at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other companies.

![Data Science Interview Prep](https://images.ctfassets.net/x78yjrjc11pq/3U4C5C0OkDR0UeGch4AmlE/7ad489430b676a088cb973307fe77884/Data_Science_Interview_Prep_Course.jpeg?w=800&h=800&fm=webp&q=75)

### [Data Science Interview Prep](https://www.aced.io/courses/data-science)

We cover statistics, experimentation, coding, SQL, machine learning, behavioral interviews, mock interviews, frameworks, and advice from senior candidates for data-science roles at Google, Amazon, Microsoft, Meta, Apple, and other companies.

## Run code

The coding workspace includes language selection, an editor, output and test-results tabs, and a console. [Sign up to run code](https://www.aced.io/signup?src=lesson).

## Aced resources

- [All questions](https://www.aced.io/questions)
- [Courses](https://www.aced.io/courses?src=nav)
- [Interview experiences](https://www.aced.io/experiences?src=nav)
- [Practice](https://www.aced.io/practice?src=nav)
- [Coaching](https://www.aced.io/coaching?src=nav)
- [Pricing](https://www.aced.io/upgrade?src=nav)
- [Log in](https://www.aced.io/login?src=nav)
- [Sign up](https://www.aced.io/signup?src=nav)

---

[Read this page’s summary](https://www.aced.io/agents/api/public/v1/page-tldr?url=https%3A%2F%2Fwww.aced.io%2Fquestions%2F3891%2Fedit-distance&trace=t_679ff9ab98f3)

## Ask a follow-up about this page

Need a more specific answer? Ask the exact question you have. It returns a fresh, cited answer from Aced (formerly Exponent)’s knowledge base. No account or API key required.

Open this URL with your own question, URL-encoded. Include your question in q. All research inputs are optional; no account or setup.

`GET https://www.aced.io/agents/agent/faq?q={question}&trace=t_679ff9ab98f3`

[Tool guide and examples](https://www.aced.io/agents/agent-access) · [OpenAPI](https://www.aced.io/agents/api/public/v1/openapi.json) · [Page TLDR form](https://www.aced.io/agents/agent-tools/page-tldr?url=https%3A%2F%2Fwww.aced.io%2Fquestions%2F3891%2Fedit-distance). Opening a form does not execute a tool.