DSA interview question
A search engine receives queries typed without spaces, like "applepenapple", and needs to know whether the text can be split into a sequence of dictionary words (words may be reused). The recursive idea is simple: try every dictionary word that matches at the current position and recurse on the rest. But the same suffix gets re-examined again and again, which is exponential for inputs like "aaaa…ab". Remembering the answer for each start position (memoisation) makes it O(n · L) substring checks, where L is the longest word.
Example: "leetcode", dictionary ["leet", "code"] → true.
bool wordBreak(const string& s, const vector<string>& wordDict);
Input (s, dict) | Output | Explanation |
|---|---|---|
("leetcode", [leet, code]) | true | leet + code |
("applepenapple", [apple, pen]) | true | Words can be reused |
("catsandog", [cats, dog, sand, and, cat]) | false | |
("aaaaaaa", [aaaa, aaa]) | true | aaa + aaaa |
("aaaaaaaaaaaaaaaaaaaaaaaaaaaaab", [a, aa, aaa, aaaa]) | false | Exponential without memoisation |
(Confirm: dictionary words can be reused; the whole string must be used; words are distinct and non-empty.)
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