Detect the First Repeated N-Gram in a Model Completion
Last updated: November 29, 2026
Quick Overview
Given a list of tokens from a generated completion and an integer n, return the start indices of the first occurrence and the first repeat of the earliest n-gram that appears twice, or None if no n-gram repeats.
OpenAI
November 29, 20260
0
0 solved
Given a list of tokens from a generated completion and an integer n, return the start indices of the first occurrence and the first repeat of the earliest n-gram that appears twice, or None if no n-gram repeats.
Degenerate repetition is a known failure mode of language model sampling, and detectors like this run in evaluation tooling and in no-repeat n-gram constraints at decode time. The OpenAI phone screen version checks hashing of sliding tuples, precise definition of what 'first' means, and clean handling of short inputs.
What the Interviewer Expects
- Clarify that 'first' means the earliest position where a repeat is discovered
- Use a hash map from n-gram tuple to first index
- Handle n larger than the sequence and non-positive n
- State the time and memory cost including the n factor
- Mention a rolling hash to drop the n factor
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
- Use a rolling hash so each window costs O(1): how do you handle collisions?
- Report every n-gram that repeats at least k times.
- During generation, block any token that would complete a repeated n-gram: what state must the decoder keep?
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:
tokensandn. - Scan windows left to right; the answer is the first window whose n-gram was already seen.
- Return
(first_index, repeat_index); windows may overlap (a a awithn=2g...
High-Level Design
Slide a window of size n across the tokens. Convert each window to a tuple (hashable) and look it up in a dictionary of first positions. The first hit is the answer because we scan in order of the r...