DSA interview question
A word game asks players to turn one word into another by changing one letter at a time, where every intermediate word must be in the dictionary. What's the fewest words in such a sequence (counting both ends), or 0 if it's impossible? Treat words as vertices and one-letter changes as edges, and this is a shortest path in an unweighted graph, so BFS. Neighbours are generated on the fly by trying every letter at every position and keeping only dictionary words.
Example: hit → cog with dictionary [hot, dot, dog, lot, log, cog] → 5 (hit → hot → dot → dog → cog).
int ladderLength(const string& beginWord, const string& endWord, const vector<string>& wordList);
Input (begin, end, dictionary) | Output | Explanation |
|---|---|---|
(hit, cog, [hot,dot,dog,lot,log,cog]) | 5 | hit hot dot dog cog |
(hit, cog, [hot,dot,dog,lot,log]) | 0 | cog isn't in the dictionary |
(a, c, [a,b,c]) | 2 | a → c directly |
(hot, dog, [hot,dog]) | 0 | Two letters differ, and nothing is in between |
(lost, cost, [most,fost,cost,host,lost]) | 2 |
(Confirm: all words have the same length and are lowercase; the begin word need not be in the dictionary, but the end word must be.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in