Word Ladder – Shortest Chain To Reach Target Word
Last Updated : 05 May, 2025
Given an array of strings arr[], and two different strings start and target, representing two words. The task is to find the length of the smallest chain from string start to target, such that only one character of the adjacent words differs and each word exists in arr[].
Note: Print 0 if it is not possible to form a chain. Each word in array arr[] is of same size m and contains only lowercase English alphabets.
Examples:
Input: start = “toon”, target = “plea”, arr[] = [“poon”, “plee”, “same”, “poie”, “plea”, “plie”, “poin”]
Output: 7
Explanation: toon → poon → poin → poie → plie → plee → plea
Input: start = “abcv”, target = “ebad”, arr[] = [“abcd”, “ebad”, “ebcd”, “xyza”]
Output: 4
Explanation: abcv → abcd → ebcd → ebad
[Naive Approach]: Using backtracking, explore all possible path
We use backtracking to solve this problem because it allows us to systematically explore all possible transformation sequences from the start word to the target word while ensuring we don’t revisit the same word within a given path. In each step, we try every possible one-letter change in the current word and proceed recursively if the resulting word exists in the dictionary and hasn’t been visited yet.Backtracking enables the algorithm to “go back” once it reaches a dead end or completes a path, and then try a different option.
This is especially useful in problems like this where multiple paths exist, and we need to find the shortest valid transformation sequence. Although this method is not the most optimized, it is conceptually simple and effective for smaller datasets where performance is not a critical issue. By exploring all valid transformation paths, it guarantees that the minimum number of steps is found among all possible sequences.
C++ #include <iostream> #include <vector> #include <string> #include <map> #include <climits> #include <algorithm> using namespace std; // Recursive function to find the shortest transformation chain int minWordTransform(string start, string target, map<string, int> &mp) { // If start word is the same as target, no transformation is needed if (start == target) return 1; int mini = INT_MAX; // Mark current word as visited mp[start] = 1; // Try changing each character of the word for (int i = 0; i < start.size(); i++) { char originalChar = start[i]; // Try all possible lowercase letters at position i for (char ch = 'a'; ch <= 'z'; ch++) { start[i] = ch; // If the new word exists in dictionary and is not visited if (mp.find(start) != mp.end() && mp[start] == 0) { // Recursive call for next transformation mini = min(mini, 1 + minWordTransform(start, target, mp)); } } // Restore original character before moving to the next position start[i] = originalChar; } // Mark current word as unvisited (backtracking) mp[start] = 0; return mini; } // Wrapper function to prepare the map and call recursive function int wordLadder(string start, string target, vector<string>& arr) { map<string, int> mp; // Initialize all words from the dictionary as unvisited for (auto word : arr) { mp[word] = 0; } int result = minWordTransform(start, target, mp); if(result==INT_MAX)result = 0; return result; } // Driver code int main() { vector<string> arr = {"poon", "plee", "same", "poie", "plie", "poin", "plea"}; string start = "toon"; string target = "plea"; cout << wordLadder(start, target, arr) << endl; return 0; }
Java import java.util.*; public class GfG { // Recursive function to find the shortest transformation chain public static int minWordTransform(String start, String target, Map<String, Integer> mp) { // If start word is the same as target, no transformation is needed if (start.equals(target)) return 1; int mini = Integer.MAX_VALUE; // Mark current word as visited mp.put(start, 1); // Try changing each character of the word for (int i = 0; i < start.length(); i++) { char[] chars = start.toCharArray(); char originalChar = chars[i]; // Try all possible lowercase letters at position i for (char ch = 'a'; ch <= 'z'; ch++) { chars[i] = ch; String transformed = new String(chars); // If the new word exists in dictionary and is not visited if (mp.containsKey(transformed) && mp.get(transformed) == 0) { // Recursive call for next transformation mini = Math.min(mini, 1 + minWordTransform(transformed, target, mp)); } } // Restore original character before moving to the next position chars[i] = originalChar; } // Mark current word as unvisited (backtracking) mp.put(start, 0); return mini; } // Wrapper function to prepare the map and call recursive function public static int wordLadder(String start, String target, ArrayList<String> arr) { Map<String, Integer> mp = new HashMap<>(); // Initialize all words from the dictionary as unvisited for (String word : arr) { mp.put(word, 0); } int result = minWordTransform(start, target, mp); if(result==Integer.MAX_VALUE) result = 0; return result; } public static void main(String[] args) { ArrayList<String> arr = new ArrayList<>(Arrays.asList( "poon", "plee", "same", "poie", "plie", "poin", "plea")); String start = "toon"; String target = "plea"; System.out.println(wordLadder(start, target, arr)); } }
Python # Recursive function to find the shortest transformation chain def minWordTransform(start, target, mp): # If start word is the same as target, no transformation is needed if start == target: return 1 mini = float('inf') # Mark current word as visited mp[start] = 1 # Try changing each character of the word for i in range(len(start)): original_char = start[i] # Try all possible lowercase letters at position i for ch in 'abcdefghijklmnopqrstuvwxyz': new_word = start[:i] + ch + start[i+1:] # If the new word exists in dictionary and is not visited if new_word in mp and mp[new_word] == 0: # Recursive call for next transformation mini = min(mini, 1 + minWordTransform(new_word, target, mp)) # Mark current word as unvisited (backtracking) mp[start] = 0 return mini # Wrapper function to prepare the map and call recursive function def wordLadder(start, target, arr): mp = {word: 0 for word in arr} result = minWordTransform(start, target, mp) if(result == float('inf')): result = 0 return result # Driver code arr = ["poon", "plee", "same", "poie", "plie", "poin", "plea"] start = "toon" target = "plea" print(wordLadder(start, target, arr))
C# using System; using System.Collections.Generic; class GfG { // Recursive function to find the shortest transformation chain static int MinWordTransform(string start, string target, Dictionary<string, int> mp){ // If start word is the same as target, no transformation is needed if (start == target) return 1; int mini = int.MaxValue; // Mark current word as visited mp[start] = 1; // Try changing each character of the word for (int i = 0; i < start.Length; i++) { char[] chars = start.ToCharArray(); char originalChar = chars[i]; // Try all possible lowercase letters at position i for (char ch = 'a'; ch <= 'z'; ch++) { chars[i] = ch; string transformed = new string(chars); // If the new word exists in dictionary and is not visited if (mp.ContainsKey(transformed) && mp[transformed] == 0) { // Recursive call for next transformation mini = Math.Min(mini, 1 + MinWordTransform(transformed, target, mp)); } } // Restore original character before moving to the next position chars[i] = originalChar; } // Mark current word as unvisited (backtracking) mp[start] = 0; return mini; } // Wrapper function to prepare the map and call recursive function static int WordLadder(string start, string target, List<string> arr){ Dictionary<string, int> mp = new Dictionary<string, int>(); // Initialize all words from the dictionary as unvisited foreach (var word in arr){ mp[word] = 0; } int result = minWordTransform(start, target, mp); if(result == int.MaxValue)result = 0; return result; } static void Main(string[] args){ List<string> arr = new List<string> { "poon", "plee", "same", "poie", "plie", "poin", "plea" }; string start = "toon"; string target = "plea"; Console.WriteLine(WordLadder(start, target, arr)); } }
JavaScript // Recursive function to find the shortest transformation chain function minWordTransform(start, target, mp) { // If start word is the same as target, no transformation is needed if (start === target) return 1; let mini = Infinity; // Mark current word as visited mp[start] = 1; // Try changing each character of the word for (let i = 0; i < start.length; i++) { let originalChar = start[i]; // Try all possible lowercase letters at position i for (let chCode = 97; chCode <= 122; chCode++) { let ch = String.fromCharCode(chCode); let newWord = start.slice(0, i) + ch + start.slice(i + 1); // If the new word exists in dictionary and is not visited if (mp.hasOwnProperty(newWord) && mp[newWord] === 0) { // Recursive call for next transformation mini = Math.min(mini, 1 + minWordTransform(newWord, target, mp)); } } } // Mark current word as unvisited (backtracking) mp[start] = 0; return mini; } // Wrapper function to prepare the map and call recursive function function wordLadder(start, target, arr) { let mp = {}; for (let word of arr) { mp[word] = 0; } let result = minWordTransform(start, target, mp); if(result == Infinity)result = 0; return result; } // Driver code let arr = ["poon", "plee", "same", "poie", "plie", "poin", "plea"]; let start = "toon"; let target = "plea"; console.log(wordLadder(start, target, arr));
Time Complexity: O(N⋅26L)), where N is the number of words in the dictionary and L is the length of each word.
Space Complexity: O(N) for storing the dictionary map and the recursive call stack, which can go up to N in the worst case.
Using Breadth First Search
The idea is to use BFS to find the smallest chain between start and target. To do so, create a queue words to store the word to visit and push start initially. At each level, go through all the elements stored in queue words, and for each element, alter all of its character for ‘a’ to ‘z‘ and one by one and check if the new word is in dictionary or not. If found, push the new word in queue, else continue. Each level of queue defines the length of chain, and once the target is found return the value of that level + 1.
C++ // C++ program to find length of the shortest // chain transformation from start to target #include <bits/stdc++.h> using namespace std; int wordLadder(string start, string target, vector<string>& arr) { // set to keep track of unvisited words unordered_set<string> st(arr.begin(), arr.end()); // store the current chain length int res = 0; int m = start.length(); // queue to store words to visit queue<string> words; words.push(start); while (!words.empty()) { res++; int len = words.size(); // iterate through all words at same level for (int i = 0; i < len; ++i) { string word = words.front(); words.pop(); // For every character of the word for (int j = 0; j < m; ++j) { // Retain the original character // at the current position char ch = word[j]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { word[j] = c; // skip the word if already added // or not present in set if (st.find(word) == st.end()) continue; // If target word is found if (word == target) return res + 1; // remove the word from set st.erase(word); // And push the newly generated word // which will be a part of the chain words.push(word); } // Restore the original character // at the current position word[j] = ch; } } } return 0; } int main() { vector<string> arr = {"poon", "plee", "same", "poie", "plie", "poin", "plea"}; string start = "toon"; string target = "plea"; cout << wordLadder(start, target, arr); return 0; }
Java import java.util.*; class GfG { static int wordLadder(String start, String target, String[] arr) { // Set to keep track of unvisited words Set<String> st = new HashSet<String>(); for(int i = 0; i < arr.length; i++) st.add(arr[i]); // Store the current chain length int res = 0; int m = start.length(); // Queue to store words to visit Queue<String> words = new LinkedList<>(); words.add(start); while (!words.isEmpty()) { int len = words.size(); res++; // Iterate through all words at the same level for (int i = 0; i < len; ++i) { String word = words.poll(); // For every character of the word for (int j = 0; j < m; ++j) { // Retain the original character // at the current position char[] wordArr = word.toCharArray(); char ch = wordArr[j]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { wordArr[j] = c; String newWord = new String(wordArr); // Skip the word if already added // or not present in set if (!st.contains(newWord)) continue; // If target word is found if (newWord.equals(target)) return res + 1; // Remove the word from set st.remove(newWord); // And push the newly generated word // which will be a part of the chain words.add(newWord); } // Restore the original character wordArr[j] = ch; } } } return 0; } public static void main(String[] args) { String[] arr = new String[]{"poon", "plee", "same", "poie", "plie", "poin", "plea"}; String start = "toon"; String target = "plea"; System.out.println(wordLadder(start, target, arr)); } }
Python # Python program to find length of the shortest # chain transformation from start to target from collections import deque def wordLadder(start, target, arr): if (start == target): return 0 # set to keep track of unvisited words st = set(arr) # store the current chain length res = 0 m = len(start) # queue to store words to visit words = deque() words.append(start) while words: res+=1 length = len(words) # iterate through all words at same level for _ in range(length): word = words.popleft() # For every character of the word for j in range(m): # Retain the original character # at the current position ch = word[j] # Replace the current character with # every possible lowercase alphabet for c in range(ord('a'), ord('z') + 1): word = word[:j] + chr(c) + word[j+1:] # skip the word if already added # or not present in set if word not in st: continue # If target word is found if word == target: return res + 1 # remove the word from set st.remove(word) # And push the newly generated word # which will be a part of the chain words.append(word) # Restore the original character # at the current position word = word[:j] + ch + word[j+1:] return 0 if __name__ == "__main__": arr = ["poon", "plee", "same", "poie", "plie", "poin", "plea"] start = "toon" target = "plea" print(wordLadder(start, target, arr))
C# // C# program to find length of the shortest // chain transformation from start to target using System; using System.Collections.Generic; class GfG{ static int WordLadder(string start, string target, string[] arr) { if(start == target) return 0; // set to keep track of unvisited words HashSet<string> st = new HashSet<string>(arr); // store the current chain length int res = 0; int m = start.Length; // queue to store words to visit Queue<string> words = new Queue<string>(); words.Enqueue(start); while (words.Count > 0) { res += 1; int len = words.Count; // iterate through all words at same level for (int i = 0; i < len; ++i) { string word = words.Dequeue(); // For every character of the word for (int j = 0; j < m; ++j) { // Retain the original character // at the current position char[] wordArray = word.ToCharArray(); // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { wordArray[j] = c; string newWord = new string(wordArray); // skip the word if already added // or not present in set if (!st.Contains(newWord)) continue; // If target word is found if (newWord == target) return res + 1; // remove the word from set st.Remove(newWord); // And push the newly generated word // which will be a part of the chain words.Enqueue(newWord); } } } } return 0; } static void Main() { string[] arr = { "poon", "plee", "same", "poie", "plie", "poin", "plea" }; string start = "toon"; string target = "plea"; Console.WriteLine(WordLadder(start, target, arr)); } }
JavaScript // JavaScript program to find length of the shortest // chain transformation from start to target function wordLadder(start, target, arr) { // set to keep track of unvisited words let st = new Set(arr); // store the current chain length let res = 0; let m = start.length; // queue to store words to visit let words = []; words.push(start); while (words.length > 0) { ++res; let len = words.length; // iterate through all words at same level for (let i = 0; i < len; ++i) { let word = words.shift(); // For every character of the word for (let j = 0; j < m; ++j) { // Retain the original character // at the current position let wordArray = word.split(''); let ch = wordArray[j]; // Replace the current character with // every possible lowercase alphabet for (let c = 'a'.charCodeAt(0); c <= 'z'.charCodeAt(0); ++c) { wordArray[j] = String.fromCharCode(c); let newWord = wordArray.join(''); // skip the word if already added // or not present in set if (!st.has(newWord)) continue; // If target word is found if (newWord === target) return res + 1; // remove the word from set st.delete(newWord); // And push the newly generated word // which will be a part of the chain words.push(newWord); } // Restore the original character // at the current position wordArray[j] = ch; } } } return 0; } // Driver code let arr = ["poon", "plee", "same", "poie", "plie", "poin", "plea"]; let start = "toon"; let target = "plea"; console.log(wordLadder(start, target, arr));
Time Complexity: O(26 * n * m * m) = O(n * m * m), where n is the size of arr[] and m is the length of each word.
Auxiliary Space: O(n * m)
Similar Reads
Graph Algorithms
Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. BasicsGraph and its representationsBFS and DFS Breadt
3 min read
Introduction to Graph Data Structure
Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
15+ min read
Graph and its representations
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
12 min read
Types of Graphs with Examples
A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
9 min read
Basic Properties of a Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are kn
4 min read
Applications, Advantages and Disadvantages of Graph
Graph is a non-linear data structure that contains nodes (vertices) and edges. A graph is a collection of set of vertices and edges (formed by connecting two vertices). A graph is defined as G = {V, E} where V is the set of vertices and E is the set of edges. Graphs can be used to model a wide varie
7 min read
Transpose graph
Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Giv
9 min read
Difference Between Graph and Tree
Graphs and trees are two fundamental data structures used in computer science to represent relationships between objects. While they share some similarities, they also have distinct differences that make them suitable for different applications. What is Graph?A graph data structure is a collection o
2 min read
BFS and DFS on Graph
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Depth First Search or DFS for a Graph
In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
13 min read
Applications, Advantages and Disadvantages of Depth First Search (DFS)
Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
4 min read
Applications, Advantages and Disadvantages of Breadth First Search (BFS)
We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
4 min read
Iterative Depth First Traversal of Graph
Given a directed Graph, the task is to perform Depth First Search of the given graph. Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list. Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pic
10 min read
BFS for Disconnected Graph
In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
14 min read
Transitive Closure of a Graph using DFS
Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: Transit
8 min read
Difference between BFS and DFS
Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS st
2 min read
Cycle in a Graph
Detect Cycle in a Directed Graph
Given the number of vertices V and a list of directed edges, determine whether the graph contains a cycle or not. Examples: Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 0 Input: V = 4, edges[][] = [[0, 1], [0, 2
15+ min read
Detect cycle in an undirected graph
Given an undirected graph, the task is to check if there is a cycle in the given graph. Examples: Input: V = 4, edges[][]= [[0, 1], [0, 2], [1, 2], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 1 â 0 Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]] Output: falseExplana
8 min read
Detect Cycle in a directed graph using colors
Given a directed graph represented by the number of vertices V and a list of directed edges, determine whether the graph contains a cycle. Your task is to implement a function that accepts V (number of vertices) and edges (an array of directed edges where each edge is a pair [u, v]), and returns tru
9 min read
Detect a negative cycle in a Graph | (Bellman Ford)
Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directe
15+ min read
Cycles of length n in an undirected and connected graph
Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
10 min read
Detecting negative cycle using Floyd Warshall
We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative. Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some adva
12 min read
Clone a Directed Acyclic Graph
A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
12 min read