A gene is a string of 8 letters, each one of A, C, G or T. A mutation changes exactly one letter.
You are given startGene, endGene and a list bank of allowed genes. Every gene you pass through after the start must be in bank; the start itself need not be. Return the fewest mutations that turn startGene into endGene, or −1 if it cannot be done.
Example 1
Input: startGene = "AAAAACCC", endGene = "AAATGCCT",
bank = ["AAAAACCT", "GAAAACCT", "AAATACCC",
"AAATACCT", "AAATGCCT"]
Output: 3
Why: AAAAACCC → AAAAACCT → AAATACCT → AAATGCCT2 more examples and the constraints
Example 2
Input: startGene = "CCCCGGGG", endGene = "CCCCGGGT",
bank = ["CCCCGGGT"]
Output: 1
Why: one letter changes, and the result is in the bankExample 3
Input: startGene = "TTTTTTTT", endGene = "TTTTTTGG",
bank = ["TTTTTTGG"]
Output: -1
Why: two letters differ and no gene in between is allowedConstraints
- 0 ≤ length of bank ≤ 10
- startGene, endGene and every bank gene have exactly 8 letters
- Letters are only A, C, G and T
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DFS over every pathO(b!·b·L)
- BFS by mutationsO(b·L·4)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work as the bank grows | Verdict |
|---|---|---|---|
| DFS over every path | O(b!·b·L) | Correct, but explores every route | |
| BFS by mutations | O(b·L·4) | Best; first arrival is shortest |
b = genes in the bank, L = 8 letters per gene.
Edge cases to test
- endGene not in the bank. No path can end there, so the answer is −1 even if it is one letter away.
- Empty bank. Nothing is reachable; return −1 unless startGene already equals endGene.
- Start equals end. Zero mutations are needed; return 0.
- Start is in the bank. It must not be counted as a step or queued twice.
- Dead ends. A gene with no unvisited neighbour simply adds nothing to the queue.
Common mistakes
- Marking genes as seen when they are popped instead of when they are queued, so a gene can be queued many times.
- Allowing endGene even when it is missing from the bank.
- Counting levels wrong: the start is 0 mutations, its neighbours are 1.
How to talk through it
- 1Clarify. Must endGene be in the bank? Is the start valid without being in it? What if start equals end?
- 2Model it as a graph. Genes are nodes; an edge joins two genes one letter apart. We want the shortest path.
- 3Say why BFS. Edges are unweighted, so BFS reaches each gene first along a shortest route. DFS would need to try every path.
- 4Code the BFS. Generate neighbours by trying 4 letters in 8 spots; remove each from the set as you queue it.
- 5Test out loud. Run an unreachable end, an empty bank and start equal to end.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?