PPractick

DSA interview question

Word Break

Medium · Algorithms · Topics: recursion, dp, trie

The problem

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.

Function signature

bool wordBreak(const string& s, const vector<string>& wordDict);

Test cases

Input (s, dict)OutputExplanation
("leetcode", [leet, code])trueleet + code
("applepenapple", [apple, pen])trueWords can be reused
("catsandog", [cats, dog, sand, and, cat])false
("aaaaaaa", [aaaa, aaa])trueaaa + aaaa
("aaaaaaaaaaaaaaaaaaaaaaaaaaaaab", [a, aa, aaa, aaaa])falseExponential without memoisation

(Confirm: dictionary words can be reused; the whole string must be used; words are distinct and non-empty.)

How interviewers phrase it

Clarifying questions to ask

  1. Can words be reused? (Yes.)
  2. How large are s and the dictionary? (s up to about 300 characters.)
  3. Do I need the segmentation, or just true/false?

Follow-ups to expect

  1. "What's the plain recursion?"
  2. "Why does memoisation work?"
  3. "Bottom-up version?"
  4. "How do you speed up the dictionary lookups?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in