DSA interview question
You're building a predictive text/autocomplete validator for a keyboard app. A word should only ever appear as a fully-typeable suggestion if every "intermediate stage" of typing it (every prefix) was also a valid, previously-seen word — this ensures the autocomplete tree never suggests a word the user couldn't have naturally arrived at by typing character-by-character through other valid words. Given an array of strings words, find the longest word such that every prefix of that word (of every length) also exists in words. If there's a tie in length, return the lexicographically smallest one. If no such word exists, return an empty string.
Example: words = ["w","wo","wor","worl","world"] → "world", since every prefix ("w","wo","wor","worl") is also present.
string longestWordWithAllPrefixes(vector<string>& words);
Input words | Output | Explanation |
|---|---|---|
["w","wo","wor","worl","world"] | "world" | All prefixes of "world" exist in the array |
["a","banana","app","appl","ap","apply","apple"] | "apple" | "a","ap","app","appl","apple" all exist; "apply" also valid but "apple" wins (tie-break: lexicographically smaller, or check actual lengths) |
["abc","bc","b","empty"] | "" | "abc" requires "a","ab" to exist — they don't; "bc" requires "b" — exists, but "bc" itself needs further check; no valid full chain found |
["a"] | "a" | Single character is trivially its own only prefix |
["yo","ew","fc","zrc","yodn","fcm","qm","qmz","zrc","fc","ewq","yod"] | "yodn" | Classic LeetCode example |
[] | "" | Empty input |
["xyz"] | "" | "xyz" has no prefixes "x" or "xy" present, so it's invalid |
(Always verify exact outputs by running the algorithm — manual prefix-chasing is error-prone for larger examples.)
words contain duplicates? (Shouldn't affect correctness but good to confirm — duplicates would just be redundant insertions into whatever structure I build.)words and individual word lengths? (Determines whether O(total characters) Trie approach is necessary vs. naive prefix-checking with a hash set being "good enough.")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