Word ladder I

Graphs Hard Problems Hard

Given are the two distinct words startWord and targetWord, and a list of size N, denoting wordList of unique words of equal size M. Find the length of the shortest transformation sequence from startWord to targetWord.


Keep the following conditions in mind:


  • A word can only consist of lowercase characters.
  • Only one letter can be changed in each transformation.
  • Each transformed word must exist in the wordList including the targetWord.
  • startWord may or may not be part of the wordList


Note: If there’s no possible way to transform the sequence from startWord to targetWord return 0.

Examples:

Input: wordList = ["des","der","dfr","dgt","dfs"], startWord = "der", targetWord = "dfs"

Output: 3

Explanation: The length of the smallest transformation sequence from "der" to "dfs" is 3 i.e. "der" -> (replace ‘e’ by ‘f’) -> "dfr" -> (replace ‘r’ by ‘s’) -> "dfs". So, it takes 3 different strings for us to reach the targetWord. Each of these strings are present in the wordList.

Input: wordList = ["geek", "gefk"], startWord = "gedk", targetWord= "geek"

Output: 2

Explanation: The length of the smallest transformation sequence from "gedk" to "geek" is 2 i.e. "gedk" -> (replace ‘d’ by ‘e’) -> "geek" .

So, it takes 2 different strings for us to reach the targetWord. Each of these strings are present in the wordList.

Input: wordList = ["hot", "dot", "dog", "lot", "log"], startWord = "hit", targetWord = "cog"

Constraints

  • N= Number of Words
  • M= Length of Word
  • 1 ≤ N ≤ 100
  • 1 ≤ M ≤ 10

Hints

  • Insert all words from wordList into a set (for O(1) lookups). If targetWord is not in wordList, return 0 (since transformation is impossible). Use BFS starting from startWord, with each level representing a transformation step.
  • For each word at the front of the queue, generate all possible one-letter transformations and check if they exist in wordList. If a transformation leads to targetWord, return the current depth. If all possible transformations are exhausted and targetWord is not reached, return 0.

Company Tags

Wayfair Etsy Chewy KPMG Shopify Bungie GE Healthcare Zynga Goldman Sachs Rockstar Games American Express PayPal Medtronic Roche Uber Instacart McKinsey & Company Rakuten HashiCorp Freshworks Bloomberg DoorDash Red Hat Dropbox Byju's Google Microsoft Amazon Meta Apple Netflix Adobe