DSA interview question
You're building a word-game feature (similar to a "word ladder" mode) for a vocabulary app. A word A is a predecessor of word B if you can insert exactly one letter into A (anywhere) to form B, without reordering the other letters. A string chain is a sequence of words word1 -> word2 -> ... -> wordk where each word is a predecessor of the next. Your task: given a list of words, find the length of the longest possible chain you can build (words can be reordered/picked in any order to form the chain, but each must be exactly one-insertion apart from the previous).
Example: ["a","b","ba","bca","bda","bdca"] — the chain "a" -> "ba" -> "bda" -> "bdca" has length 4.
int longestStrChain(vector<string>& words);
Input words | Output | Explanation |
|---|---|---|
["a","b","ba","bca","bda","bdca"] | 4 | "a" -> "ba" -> "bda" -> "bdca" |
["xbc","pcxbcf","xb","cxbc","pcxbc"] | 5 | "xb" -> "xbc" -> "cxbc" -> "pcxbc" -> "pcxbcf" |
["abcd","dbqca"] | 1 | "dbqca" needs 2 insertions from "abcd", not a valid predecessor step |
["a"] | 1 | Single word, chain of length 1 |
[] | 0 | Empty input |
["ab","abc","abcd","abcde"] | 4 | Each word extends the previous by exactly one letter, in order |
(Always confirm: words can be any length, duplicates possible, and a single word alone counts as a chain of length 1.)
words and max word length? (Helps decide if O(n² * L) — comparing all pairs — is acceptable, or if the "remove one character and hash" trick is expected for efficiency.)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