Hybrid run-length and bit-packing codec
I was asked this
No reports yet. Sign in to say where you were asked it.
Design an encoder and a decoder for a list of non-negative integers. The encoder compresses the list into a list of human-readable run strings. The decoder restores the original list exactly.
There are two kinds of run:
-
Run-length run:
"RLE[value, count]"meansvaluerepeatedcounttimes (count >= 1). -
Bit-packed run:
"BP[width, v1, v2, ...]"stores one or more literal values.widthis the number of bits needed for the largest value in the run (at least 1, so a run of zeros has width 1). Every value must fit inwidthbits.
Implement:
-
encode(nums: List[int], min_run: int = 3) -> List[str]: scan the input as maximal runs of equal values. A run at leastmin_runlong becomes anRLErun. Shorter runs are collected, in order, into a singleBPrun that ends just before the nextRLErun or at the end of the input. -
decode(runs: List[str]) -> List[int]: concatenate the runs. RaiseValueErroron malformed input (unknown prefix,count <= 0, an emptyBPrun, or a value wider than its declared width).
decode(encode(nums)) == nums must hold for every valid input.
Constraints
0 <= len(nums) <= 10^50 <= nums[i] < 2^31- Both operations should run in linear time.
Example 1
nums = [4, 4, 4, 4, 6, 1, 2, 2, 8, 8, 8]
encode -> ["RLE[4, 4]", "BP[3, 6, 1, 2, 2]", "RLE[8, 3]"]
The runs of 4 and 8 are long enough for RLE. The values 6, 1, 2, 2 are packed together. The largest of them is 6, which needs 3 bits.
Example 2
runs = ["BP[1, 0, 1]", "RLE[3, 2]"]
decode -> [0, 1, 3, 3]
Be ready for follow-ups: write the runs as real packed bits, choose the split by encoded size instead of a fixed threshold, stream values in and out with bounded memory, and support signed 32-bit integers.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
