Skip to content

Instantly share code, notes, and snippets.

@JodhwaniMadhur
Created January 17, 2025 02:16
Show Gist options
  • Save JodhwaniMadhur/d7c56015d7cefdf6452a4f2ca3286662 to your computer and use it in GitHub Desktop.
Save JodhwaniMadhur/d7c56015d7cefdf6452a4f2ca3286662 to your computer and use it in GitHub Desktop.
Word Ladder Solution | BFS | Python
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
#TC = O(M^2 * N) where M is the length of the words we jump on and N is the length of wordList
#SC = O(M^2 * N) where M is for words we jump on and N is the wordlist space
if endWord not in wordList:
return 0
q = deque([beginWord])
available = set(wordList)
jumps = 0
while q:
jumps+=1
n = len(q)
for i in range(n):
currWord = q.popleft()
if currWord == endWord: return jumps
for j in range(len(currWord)):
orgC = currWord[j]
for alpha in range(26):
currWord = currWord[:j] + chr(97 + alpha) + currWord[j+1:]
if(currWord in available):
q.append(currWord)
available.remove(currWord)
currWord = currWord[:j]+orgC+currWord[j+1:]
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment