Encode and Decode Varints From a Raw Byte Stream
Last updated: November 29, 2026
Quick Overview
Implement encoding and decoding of unsigned LEB128 variable-length integers, decoding a buffer that holds several varints back to back and rejecting truncated or overlong input.
Coinbase
November 29, 20260
0
0 solved
Implement encoding and decoding of unsigned LEB128 variable-length integers, decoding a buffer that holds several varints back to back and rejecting truncated or overlong input.
Coinbase services speak protobuf and gRPC internally, and blockchain node data uses similar compact integer encodings. The interviewer checks comfort with bit masks and shifts, a correct continuation-bit loop and defensive limits on untrusted input.
What the Interviewer Expects
- Use 7 payload bits per byte and the high bit as continuation
- Emit least significant groups first
- Decode multiple varints from one buffer
- Reject truncated input and values longer than 10 bytes
- Test boundaries like 127, 128 and 2^63 - 1
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 does zigzag encoding make negative numbers cheap?
- How does Bitcoin's CompactSize differ from LEB128?
- Why is a maximum length important for a network parser?
- How would you decode from a stream without loading it all into memory?
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_varint(n) for non-negative ints returns bytes. decode_varints(buf) returns the list of decoded values. Truncated final varints and varints longer than 10 bytes (enough for 64-bit) raise Val...
High-Level Design
Encoding: take the low 7 bits, shift right by 7, and set the high bit if more remains. Decoding: accumulate (b & 0x7F) << shift, increase shift by 7, and when a byte without the high bit arrives, em...