← L&T Mindtree bank

L&T Mindtree · Question 64 · Graphs

Word Ladder

GraphsJavacode⏱ O(m²n)💾 O(mn)
Service-based

Problem

You are given beginWord, endWord and wordList. Find shortest transformation sequence length.

Approach

BFS over single-letter mutations, removing visited words.

Time O(m²n)Space O(mn)

How it works

  1. 1BFS level by level from beginWord.
  2. 2Every unseen one-letter mutation is enqueued once.

Sample input / output

Input:
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output:
5

Constraints

Word lengths <= 10; wordList up to 5000.

Solution — read it, then walk it

Time O(m²n)Space O(mn)Loops 4Branches 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intladderLength(StringbeginWord, String endWord…Set<String> dict = newHashSet<>(wordList)if(!dict.contains(endWord))return 0Queue<String> q = newLinkedList<>()q.add(beginWord)DEFINE level = 1while (!q.isEmpty())DEFINE size = q.size()for (int i = 0; i <size; i++)DEFINE [] word =q.poll().toCharArray()if (newString(word).equals(endWord))return levelfor (int j = 0; j <word.length; j++)DEFINE old = word[j]for (char c = 'a'; c<= 'z'; c++)word[j] = cString ns = newString(word)if (dict.remove(ns))q.add(ns)word[j] = oldlevel++RETURN 0DEFINE static voidmain(String[] args)System.out.println(ladderLength("hit","cog", Arrays.asList("hot","dot", "dog", "lot", "log"…END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/25

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits