Determine Whether a String Can Be Segmented into Dictionary Words
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Overview: Decide whether an entire string can be segmented into reusable dictionary words. Handle overlapping candidates, the empty string, and large inputs with a dynamic program or graph search that avoids enumerating all possible segmentations.
Read the full Meta Software Engineer interview experience this question came from
Constraints
- len(s) <= 10000.
- The dictionary contains at most 5000 non-empty lowercase words.
- Duplicate dictionary entries have no additional effect.
- A dictionary word may be reused any number of times.
- Every input character must belong to exactly one selected segment.
- The empty input string is segmentable.
Examples
Input: ('applepenapple', ['apple', 'pen'])
Expected Output: True
Explanation: This is the first source example; apple can be reused around pen.
Input: ('catsandog', ['cats', 'dog', 'sand', 'and', 'cat'])
Expected Output: False
Explanation: This is the second source example; no choices cover the entire suffix.
Hints
- Track which string boundaries can be reached by complete dictionary words.
- A trie lets each reachable boundary explore only prefixes that occur in the dictionary.