Encode Token Id Sequences as Variable-Length Bytes
Last updated: November 29, 2026
Quick Overview
Write functions that encode a list of non-negative token ids into a compact byte string using 7-bit variable-length groups (high bit marks continuation) and decode it back, rejecting truncated input.
OpenAI
November 29, 20260
0
0 solved
Write functions that encode a list of non-negative token ids into a compact byte string using 7-bit variable-length groups (high bit marks continuation) and decode it back, rejecting truncated input.
Token ids from vocabularies of 100k to 200k entries are stored and shipped in huge volumes during data preparation, and most fit in two or three varint bytes instead of four. This OpenAI warm-up checks bit manipulation fluency, a clean round-trip test, and explicit handling of malformed input.
What the Interviewer Expects
- Emit 7 bits per byte, least significant group first, with the high bit for continuation
- Decode by accumulating shifted groups until a byte without the high bit
- Detect truncation when the stream ends mid-number
- Reject negative inputs or explain zigzag encoding for them
- Test boundary values like 127, 128 and large ids
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 encode negative deltas, for example when storing differences between sorted ids?
- Decoding is a hot loop: how would you speed it up for long sequences?
- Compare this with fixed 3-byte encoding for a 200k vocabulary in space and decode speed.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
encode_varints(ids) -> bytes,decode_varints(data) -> list[int].- Each id is split into 7-bit groups, lowest first; every byte except the last of an id has its high bit set.
- Decoding must exa...
High-Level Design
Encoding loops: take v & 0x7F, shift v right by 7, and set the high bit if anything remains. Decoding keeps a running value and shift: OR in each byte's low 7 bits shifted into place, and when...