Segment Text Into the Fewest Tokens From a Vocabulary

Last updated: November 29, 2026

Quick Overview

Given a string and a vocabulary of token strings, return a segmentation of the whole string into vocabulary tokens that uses as few tokens as possible, or None if no segmentation exists.

OpenAI
Coding & Algorithms
Software Engineer
OpenAI
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given a string and a vocabulary of token strings, return a segmentation of the whole string into vocabulary tokens that uses as few tokens as possible, or None if no segmentation exists.

Token counts drive both latency and price for OpenAI API users, so a question about covering text with the fewest tokens connects a standard DP to something the company cares about. Interviewers check the DP state definition, reconstruction of the actual answer (not just the count), and using the maximum token length to prune the inner loop.

What the Interviewer Expects
  • Define the DP state as the fewest tokens covering a prefix
  • Reconstruct the segmentation with parent pointers
  • Bound the inner loop by the longest vocabulary entry
  • Return a clear sentinel when no segmentation exists
  • Contrast the optimal DP with greedy longest-match
Key Topics to Cover
1D dynamic programming
string segmentation
path reconstruction
tokenization
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
  • Show an input where greedy longest-prefix matching uses more tokens than optimal.
  • Replace the set lookup with a trie: how does the complexity change?
  • Each token has a cost (for example negative log probability): minimize total cost instead.
  • How would you count the number of distinct optimal segmentations?
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: text and vocab, a set of non-empty strings.
  • Output: a list of tokens whose concatenation is text, minimizing the count, or None.
  • Empty text segments into zero tokens.
  • Any optima...
High-Level Design

Let best[i] be the fewest tokens needed to cover text[:i]. Then best[i] = 1 + min(best[j]) over all j where text[j:i] is in the vocabulary. Only j within max_len characters of i can wo...


Submit Your Answer
Markdown supported