Implement a lossless codec for arrays of 32-bit non-negative integers that combines run-length encoding (RLE) with bit-packing. The encoder should work in a single streaming pass, looking at each value once and keeping only the current run as state.
Encoding groups consecutive equal values into runs. Each run becomes one (count, value) pair, and each pair is packed into a single 64-bit integer: the upper 32 bits hold the run count and the lower 32 bits hold the value. Decoding reverses this. It unpacks each 64-bit integer into its count and value and writes the value count times.
Implement encode, decode and codec, where codec(nums) returns decode(encode(nums)). The round trip must be lossless, so codec(nums) always equals nums.
Function Signature
class Solution:
def encode(self, nums: list[int]) -> list[int]:
...
def decode(self, encoded: list[int]) -> list[int]:
...
def codec(self, nums: list[int]) -> list[int]:
...
Rules
-
A run is a maximal block of consecutive equal values, so two neighboring entries of the encoded list never carry the same value.
encode
returns the runs in input order.
-
A run with count
c
and value
v
is packed as
(c << 32) | v
, which equals
c * 2**32 + v
.
-
decode
reads the count as
packed >> 32
and the value as
packed & 0xFFFFFFFF
.
-
An empty array encodes to an empty list, and an empty encoded list decodes to an empty array.
Constraints
-
0 <= len(nums) <= 10^5
-
0 <= nums[i] <= 2^32 - 1
-
Each encoded element is a 64-bit integer with the run count in the upper 32 bits and the value in the lower 32 bits.
Examples
Input: nums = [1,1,1,2,2,3]
Output: encode(nums) = [12884901889, 8589934594, 4294967299], codec(nums) = [1,1,1,2,2,3]
The runs are (3, 1), (2, 2) and (1, 3). With 232=4294967296 they pack to 3 * 4294967296 + 1, 2 * 4294967296 + 2 and 4294967296 + 3, and decoding expands them back to the input.
Input: nums = [5,5,5,5,5]
Output: encode(nums) = [21474836485], codec(nums) = [5,5,5,5,5]
The whole array is one run of value 5 with count 5, so it packs to the single word 5 * 4294967296 + 5.
Input: nums = [4294967295,4294967295,0]
Output: encode(nums) = [12884901887, 4294967296], codec(nums) = [4294967295,4294967295,0]
The first run (2, 4294967295) fills the whole lower half: 2 * 4294967296 + 4294967295 = 12884901887. The run (1, 0) packs to exactly 4294967296, because a value of zero leaves the lower 32 bits empty.