Implement RLE and bit-packing compression
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates understanding of simple lossless compression techniques and related competencies such as string processing and parsing for run-length encoding, bit-level operations and packing for fixed-width integer compression, and algorithmic complexity analysis.
Part 1: Run-Length Encoding (RLE)
Constraints
- mode is either 'compress' or 'decompress'.
- For compression, 0 <= len(text) <= 100000.
- For compression, text contains printable ASCII characters excluding digits '0'..'9'.
- For decompression, text is well-formed as zero or more groups of <positive integer><single non-digit character>.
- Counts fit in a standard integer type, and the fully decoded output length is at most 1000000.
Examples
Input: ('compress', 'AAABCCDDDD')
Expected Output: '3A1B2C4D'
Explanation: Runs are AAA, B, CC, and DDDD, so the encoded form is 3A1B2C4D.
Input: ('decompress', '3A1B2C4D')
Expected Output: 'AAABCCDDDD'
Explanation: Expand each count-character pair back into repeated characters.
Hints
- For compression, scan left to right while tracking the current character and its run length.
- For decompression, counts may have multiple digits, so collect consecutive digits before reading the following character.
Part 2: Bit-Packing Compression for Small Integers
Constraints
- mode is either 'pack' or 'unpack'.
- For packing, 0 <= len(data) <= 100000 and every value is in [0, 15].
- For unpacking, n is a non-negative integer and len(data) == ceil(n / 2).
- For unpacking, every packed byte is in [0, 255].
- Empty input is allowed.
Examples
Input: ('pack', [3, 15, 0, 7], None)
Expected Output: [63, 7]
Explanation: [3, 15] becomes 0x3F = 63 and [0, 7] becomes 0x07 = 7.
Input: ('unpack', [63, 7], 4)
Expected Output: [3, 15, 0, 7]
Explanation: Split each byte into its high and low 4-bit parts.
Approach
Time complexity: O(n), where n is the number of 4-bit integers. Pack visits each of the n inputs once (producing ceil(n/2) bytes); unpack visits each of the ceil(n/2) bytes once and emits up to n values.
Space complexity: O(n) for the output. Pack allocates ceil(n/2) bytes; unpack allocates up to n values. Aside from the output list, only O(1) auxiliary space is used.
Hints
- To pack two 4-bit values a and b into one byte, put a in the high nibble using a << 4, then combine with b using bitwise OR.
- To unpack a byte x, recover the first value with (x >> 4) & 15 and the second with x & 15. Stop once you have produced n values.
Community answers
Answer by sincarawa