
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1000
int isOneLetterDiff(const char *a, const char *b) {
int diff = 0;
for (int i = 0; a[i]; i++) {
if (a[i] != b[i]) diff++;
if (diff > 1) return 0;
}
return diff == 1;
}
int wordLadder(char *start, char *end, char **wordList, int size) {
int visited[MAX] = {0};
char *queue[MAX];
int level[MAX];
int front = 0, rear = 0;
queue[rear] = start;
level[rear++] = 1;
while (front < rear) {
char *word = queue[front];
int currLevel = level[front++];
if (strcmp(word, end) == 0)
return currLevel;
for (int i = 0; i < size; i++) {
if (!visited[i] && isOneLetterDiff(word, wordList[i])) {
visited[i] = 1;
queue[rear] = wordList[i];
level[rear++] = currLevel + 1;
}
}
}
return 0;
}
int main() {
char *wordList[] = {"hot", "dot", "dog", "lot", "log", "cog"};
int size = 6;
printf("Length of shortest transformation: %d\n", wordLadder("hit", "cog", wordList, size));
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(m * n) | Where n is the number of words and m is the length of each word. In the best case, the target is found early in the BFS traversal, but we still generate m*26 transformations per word. |
| Average Case | O(m * n) | For each word in the wordList, up to m*26 transformations are checked, and each valid transformation is enqueued once. |
| Worst Case | O(m * n) | All words are visited and all possible transformations are generated, each requiring O(m) time. So, total operations are O(m * 26 * n) ≈ O(m * n). |