Encode and Decode Varints With ZigZag Like Protocol Buffers

Last updated: November 29, 2026

Quick Overview

Implement base-128 varint encoding and decoding for unsigned integers, plus ZigZag mapping so negative numbers stay short, and a decoder that reads a sequence of varints from a byte buffer and reports truncated input.

Google
Software Engineering Fundamentals
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Software Engineering Fundamentals
Medium

0

0

0 solved


Implement base-128 varint encoding and decoding for unsigned integers, plus ZigZag mapping so negative numbers stay short, and a decoder that reads a sequence of varints from a byte buffer and reports truncated input.

Varints are the core of the protobuf wire format used by almost every Google service, so this shows up as a fundamentals screen. The interviewer checks bit manipulation, why ZigZag exists, and robust handling of malformed bytes.

What the Interviewer Expects
  • Emit 7 bits per byte with the high bit as continuation flag
  • Explain why int32 -1 costs 10 bytes without ZigZag
  • Implement ZigZag encode and decode with shifts
  • Reject truncated or overlong input
  • Decode a stream and return the next offset
Key Topics to Cover
varint
ZigZag encoding
bit manipulation
protocol buffers
binary parsing
How to Approach This
  1. Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
  2. Choose data structures based on access patterns, not familiarity.
  3. Prefer immutable data and message passing over shared mutable state for concurrency.
  4. Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
  • Why does protobuf still use 10 bytes for negative int32 rather than 5?
  • How would you decode varints faster with SIMD or lookup tables?
  • When is fixed32 better than a varint?
  • How would you guard against a 1 GB length prefix?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice System Design Problems
Sample Answer
Requirements
  • encode_uvarint(n) for 0 <= n < 2**64 returns bytes.
  • decode_uvarint(buf, pos) returns (value, new_pos); raises on truncation or more than 10 bytes.
  • zigzag(n) and unzigzag(z) for signe...
High-Level Design

Each byte carries the low 7 bits of what remains, least significant group first, with bit 7 set when more bytes follow. 300 is 0b1_0010_1100, so the bytes are 0xAC 0x02. Small numbers take one byt...


Submit Your Answer
Markdown supported