← Deloitte bank

Deloitte · Question 70 · Graphs

Word Ladder (Length)

GraphsJavacode⏱ O(M*N*26)💾 O(N)
Service-based

Problem

Shortest transformation length from beginWord to endWord changing one char at a time.

Approach

BFS on the word graph using generic states.

Time O(M*N*26)Space O(N)

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*26)Space O(N)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 = newArrayDeque<>()q.add(beginWord)DEFINE level = 1while (!q.isEmpty())DEFINE sz = q.size()for (int i = 0; i <sz; i++)String w = q.poll()if (w.equals(endWord))return levelDEFINE [] arr =w.toCharArray()for (int j = 0; j <arr.length; j++)DEFINE old = arr[j]for (char c = 'a'; c<= 'z'; c++)arr[j] = cString ns = new String(arr)if (dict.remove(ns))q.add(ns)arr[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/26

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