Streaming Run/Bit-Pack Codec Session Simulator
Math & Bit ManipulationAuto-graded · 14 test casesLast updated
Simulate a codec session that buffers int32 values, emits run-length and bit-packed blocks on flush, and decodes block lists back to integers.
Codec Session Simulator
You are building a small compressor for signed 32-bit integers. It compresses a stream into blocks of two kinds, and it can also expand a list of blocks back into integers. Implement a function that runs a sequence of commands against one codec session and returns one result per command.
Block formats
Blocks are Python dictionaries.
Run block (a repeated value):
{"type": "R", "value": v, "count": n}
Packed block (a group of small values stored with a fixed number of bits each):
{"type": "B", "bitWidth": w, "count": n, "payload": [word0, word1, ...]}
Constants
RLE_MIN_RUN = 3MAX_BP_BLOCK = 128
Commands
commands[i] is the name of the i-th command and params[i] is its list of arguments. The function returns a list results where results[i] is the result of command i.
"add":params[i] = [value]. Appendvalueto the session's pending input. The result isNone. Ifvalueis outside the signed 32-bit range[-2^31, 2^31 - 1], raiseValueError."flush":params[i] = []. Compress all pending input into a list of blocks, as described below. The result is that list. The pending input is then cleared, so lateraddcommands start a fresh stream. Flushing with nothing pending gives[]."decode":params[i] = [block_list]. Expandblock_listinto the integers it represents and return them as a list. This command is independent of the pending input and does not change it.- Any other command name: raise
ValueError.
How flush compresses
- Split the pending input into maximal runs, each a maximal stretch of consecutive equal values.
- A run of length
>= RLE_MIN_RUNbecomes exactly one run block with its value and full length. - Runs shorter than
RLE_MIN_RUNare not run blocks. Their values, in original order, are appended to a pending group of "loose" values. Loose values from different short runs that are adjacent in the stream (no run block between them) belong to the same group. - When a run block is emitted, or the input ends, the current loose group is written out first as packed blocks. The group is cut from its start into chunks of exactly
MAX_BP_BLOCKvalues, and the last chunk may be shorter. Then the run block follows. So block order always matches input order. - For each chunk,
bitWidthis the smallestwin1..32such that every value in the chunk fits inw-bit two's complement, i.e. lies in[-2^(w-1), 2^(w-1) - 1]. countis the number of values in the chunk.
Payload layout
The payload is a list of unsigned 32-bit integers (words), packed least-significant-bit first:
- Value
iof the chunk is stored as its lowwbits (two's-complement pattern) at bit positionsi*wthroughi*w + w - 1of one long bit string. - Bit position
plives in wordp // 32, at bitp % 32(bit 0 is the least significant). A value may therefore span two consecutive words. - The payload has exactly
ceil(count * w / 32)words. Unused high bits of the last word are 0.
How decode expands
Process the blocks in order and concatenate their output:
- A run block yields
valuerepeatedcounttimes. - A packed block yields
countintegers. Readw = bitWidthbits for each value from the payload with the layout above, then sign-extend: if the top bit (bitw - 1) is set, subtract2^w. - Any other block
typeraisesValueError.
Function
Return the list of per-command results, in order. With no commands, return [].
Constraints
len(commands) == len(params).- Every
addvalue is expected to be an integer; values outside signed 32-bit range must raiseValueError. - Block lists given to
decodeare well-formed and were produced under the rules above, apart from possible unknown block types. - Run lengths can be large, so do not assume a run fits in one packed block.
- The full signed 32-bit range must be handled, including
-2^31,2^31 - 1and-1.
Examples
Example 1
Input: run_codec_session(['add', 'add', 'add', 'add', 'add', 'flush', 'decode'], [[1], [2], [3], [7], [7], [], [[{'type': 'B', 'bitWidth': 3, 'count': 3, 'payload': [209]}, {'type': 'B', 'bitWidth': 3, 'count': 2, 'payload': [63]}]]])
Output: [None, None, None, None, None, [{'type': 'B', 'bitWidth': 4, 'count': 5, 'payload': [488225]}], [1, 2, 3, -1, -1]]
Example 2
Input: run_codec_session([], [])
Output: []
Hints
Hint 1
Handle each command independently while keeping one list of pending values. Only the flush command needs real work, and it clears that list.
Hint 2
Scan for maximal runs. Long runs flush the loose values collected so far (cut into chunks of 128) and then emit one run block; short runs just join the loose group.
Hint 3
For the bit width, use the bit length of v for v >= 0 or of ~v for v < 0, plus 1. For packing, mask each value to w bits, shift it to its bit offset, and spill the high part into the next word when it crosses a 32-bit boundary. Decode by reversing this, masking, then sign-extending.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function is a small interpreter over three commands. It keeps one list of pending values. add validates and appends, decode is a pure function of its argument, and flush compresses the pending list and clears it.
Compression (flush).
- Walk the pending values and find each maximal run of equal values.
- If the run length is at least 3, first write out any loose values collected so far, then emit one run block
{"type": "R", ...}. - Otherwise, append the run's values to the loose list.
- The loose list is written out in chunks of at most 128 values from its start. For each chunk, the bit width is the maximum of the minimal two's-complement widths of its values. For
v >= 0this isv.bit_length() + 1, and forv < 0it is(~v).bit_length() + 1. - Packing masks each value to
wbits and places it at bit offseti*w. If it crosses a 32-bit word boundary, the high bits go to the next word.
Decoding. Run blocks repeat their value. Packed blocks read w bits at offset i*w, combining two words when the value straddles a boundary. They then mask to w bits and sign-extend by subtracting 2^w when the top bit is set.
Why it is correct
- Each maximal run is classified exactly once, so runs of length 3 or more always become a single run block and shorter runs always go to packed blocks.
- Pending loose values are written out before each run block and at the end, so the block order equals the input order.
- Every value in a chunk fits in the chosen width, so masking and sign extension recover it exactly. Width 32 covers
-2^31and2^31 - 1. - Two short runs next to each other can never have equal values, since they would be one run. So no run-block opportunity is missed.
- Clearing the pending list on
flushgives each flush a fresh stream.
Complexity
Let n be the number of values added and m the total number of values in the decoded blocks.
- Time:
O(n)for adds and flushes combined, since each value is scanned once and packed once with constant-time bit operations. Decoding isO(m). - Space:
O(n)for the pending list and the output blocks.
Reference solution
from typing import List
RLE_MIN_RUN = 3
MAX_BP_BLOCK = 128
INT_LOW = -(1 << 31)
INT_HIGH = (1 << 31) - 1
WORD_MASK = 0xFFFFFFFF
def _width_of(value: int) -> int:
base = value if value >= 0 else ~value
return base.bit_length() + 1
def _pack_values(values: List[int], width: int) -> List[int]:
words = [0] * ((len(values) * width + 31) // 32)
mask = (1 << width) - 1
pos = 0
for v in values:
bits = v & mask
idx, off = divmod(pos, 32)
words[idx] |= (bits << off) & WORD_MASK
if off + width > 32:
words[idx + 1] |= bits >> (32 - off)
pos += width
return words
def _unpack_block(block: dict) -> List[int]:
width = block["bitWidth"]
words = block["payload"]
mask = (1 << width) - 1
out = []
pos = 0
for _ in range(block["count"]):
idx, off = divmod(pos, 32)
bits = words[idx] >> off
if off + width > 32:
bits |= words[idx + 1] << (32 - off)
bits &= mask
if bits >> (width - 1):
bits -= 1 << width
out.append(bits)
pos += width
return out
def _compress(values: List[int]) -> List[dict]:
blocks = []
loose = []
def write_loose():
nonlocal loose
for start in range(0, len(loose), MAX_BP_BLOCK):
chunk = loose[start:start + MAX_BP_BLOCK]
width = max(_width_of(v) for v in chunk)
blocks.append({
"type": "B",
"bitWidth": width,
"count": len(chunk),
"payload": _pack_values(chunk, width),
})
loose = []
i = 0
n = len(values)
while i < n:
j = i + 1
while j < n and values[j] == values[i]:
j += 1
length = j - i
if length >= RLE_MIN_RUN:
write_loose()
blocks.append({"type": "R", "value": values[i], "count": length})
else:
loose.extend(values[i:j])
i = j
write_loose()
return blocks
def _expand(blocks: List[dict]) -> List[int]:
out = []
for block in blocks:
kind = block["type"]
if kind == "R":
out.extend([block["value"]] * block["count"])
elif kind == "B":
out.extend(_unpack_block(block))
else:
raise ValueError("Unknown block type")
return out
def run_codec_session(commands: List[str], params: List[List]) -> List:
pending = []
results = []
for cmd, args in zip(commands, params):
if cmd == "add":
v = args[0]
if not INT_LOW <= v <= INT_HIGH:
raise ValueError("Input must be a signed 32-bit integer")
pending.append(v)
results.append(None)
elif cmd == "flush":
results.append(_compress(pending))
pending = []
elif cmd == "decode":
results.append(_expand(args[0]))
else:
raise ValueError("Unknown operation")
return results