KatInterview

Streaming Run/Bit-Pack Codec Session Simulator

Math & Bit ManipulationAuto-graded · 14 test cases
HardAuto-gradedMath & Bit Manipulationbit-manipulationcompressionsimulation

Last 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 = 3
  • MAX_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]. Append value to the session's pending input. The result is None. If value is outside the signed 32-bit range [-2^31, 2^31 - 1], raise ValueError.
  • "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 later add commands start a fresh stream. Flushing with nothing pending gives [].
  • "decode": params[i] = [block_list]. Expand block_list into 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

  1. Split the pending input into maximal runs, each a maximal stretch of consecutive equal values.
  2. A run of length >= RLE_MIN_RUN becomes exactly one run block with its value and full length.
  3. Runs shorter than RLE_MIN_RUN are 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.
  4. 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_BLOCK values, and the last chunk may be shorter. Then the run block follows. So block order always matches input order.
  5. For each chunk, bitWidth is the smallest w in 1..32 such that every value in the chunk fits in w-bit two's complement, i.e. lies in [-2^(w-1), 2^(w-1) - 1].
  6. count is 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 i of the chunk is stored as its low w bits (two's-complement pattern) at bit positions i*w through i*w + w - 1 of one long bit string.
  • Bit position p lives in word p // 32, at bit p % 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 value repeated count times.
  • A packed block yields count integers. Read w = bitWidth bits for each value from the payload with the layout above, then sign-extend: if the top bit (bit w - 1) is set, subtract 2^w.
  • Any other block type raises ValueError.

Function

Return the list of per-command results, in order. With no commands, return [].

Constraints

  • len(commands) == len(params).
  • Every add value is expected to be an integer; values outside signed 32-bit range must raise ValueError.
  • Block lists given to decode are 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 - 1 and -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.