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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

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
Dynamic Programming
Strings
Hash Set
Backtracking
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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 ...


Submit Your Answer
Markdown supported