Segment a Spaceless Search Query into Dictionary Words
Last updated: November 29, 2026
Quick Overview
Given a query string with no spaces and a dictionary of words, return one way to split the query into dictionary words separated by spaces, or None if no split exists.
0
0
0 solved
Given a query string with no spaces and a dictionary of words, return one way to split the query into dictionary words separated by spaces, or None if no split exists.
Framed around query understanding in Google Search (users typing newyorkhotels), this tests whether you turn exponential backtracking into dynamic programming and can reconstruct an answer, not just a boolean. Interviewers often follow up with ranking among multiple segmentations.
What the Interviewer Expects
- Identifies overlapping subproblems that make plain backtracking exponential
- Defines dp over prefixes and stores a back pointer for reconstruction
- Limits inner loops by the maximum dictionary word length
- Returns an actual segmentation
- Discusses how to choose the best segmentation when several exist
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return all segmentations; what is the output-sensitive complexity?
- Choose the most likely segmentation given word frequencies.
- How would you handle a dictionary of millions of words in limited memory?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: string
s, list of dictionary words. - Output: a space-separated segmentation using only dictionary words,
""for empty input, None if impossible. - Words may be reused....
High-Level Design
Let back[i] be the start index of the last word in some valid segmentation of s[:i], or -1 if s[:i] cannot be segmented; back[0] = 0 as the base case. For each end i, try each start j from `i ...