Problem Statement
You are given a source word and a target word. In each step, you can modify exactly one character in the word. After each modification, the resulting word must exist in the given array arr. Return the minimum number of operations required to transform the source word into the target word.
Clarifications
Are all characters lowercase? → Yes
Can source be equal to target? → Yes
Can target be absent from arr? → Yes
Do all words have the same length? → Yes
Approach
This is a typical Breadth-First Search (BFS) problem.
First, handle edge cases such as when source == target or when target is not in arr. After that, we perform BFS:
Add source to the queue
Repeatedly pop from the queue and explore its neighbors
There are two ways to generate neighbors:
Compare with every word in arr and check if they differ by exactly one character
For each position in the current word, try replacing it with all possible letters (a–z) and check if the new word exists in the set
Skip already visited words; otherwise mark them visited and push into the queue
If we reach the target, return the distance; otherwise return -1
Follow-up: Return the transformation path
We can keep track of each word’s predecessor during BFS.
Once we reach the target, we backtrack using the predecessor map to reconstruct the path from target to source, and then reverse it to get the final answer.