Count Ways to Segment a Caption Into Known Hashtag Words
Last updated: November 29, 2026
Quick Overview
Users often write hashtags without spaces, like 'dancechallengeduet'. Given a dictionary of known words and a lowercase string, count how many ways the string can be split into a sequence of dictionary words, modulo 10^9 + 7.
TikTok
November 29, 20260
0
0 solved
Users often write hashtags without spaces, like 'dancechallengeduet'. Given a dictionary of known words and a lowercase string, count how many ways the string can be split into a sequence of dictionary words, modulo 10^9 + 7.
TikTok search and hashtag understanding depend on segmenting concatenated tags into words, so this word break variant appears in online assessments. The grader checks the DP recurrence, efficient substring lookups, and handling the modulus.
What the Interviewer Expects
- Defines ways[i] as the number of segmentations of the prefix of length i
- Limits inner loop to the maximum dictionary word length
- Uses a set for O(1) membership checks
- Applies the modulus to avoid huge numbers
- Explains how to switch from counting to returning one segmentation
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
- How would you return the most likely segmentation using word frequencies?
- How would you handle a dictionary of millions of words, perhaps with a trie?
- What if some characters are typos and you allow one edit per word?
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:
s(length up to a few thousand),words: list[str]. - Output: number of segmentations modulo 1,000,000,007.
- Empty string has exactly one segmentation (the empty sequence)....
High-Level Design
Let ways[i] be the number of ways to segment s[:i]. Then ways[i] = sum(ways[j]) for every j where s[j:i] is a dictionary word. ways[0] = 1.
The inner loop only needs to look back maxlen c...