AlgoMaster Logo
AlgoMasterRun-Length Encode Dataeasy

Run-Length Encode Data

easy

Run-length encoding compresses data by replacing each consecutive run of equal values with the value and the number of times it appears. It is effective for repetitive data in columnar databases, bitmap indexes, and image formats.

Design a RunLengthEncoder class:

  • RunLengthEncoder() creates a stateless encoder.
  • int[] encode(int[] data) returns a flattened run-length encoding in the form [value1, count1, value2, count2, ...].

Runs are based on consecutive values. Equal values separated by another value belong to different runs. A run of length one still emits its value followed by 1. Return an empty array when data is empty, and do not modify data.

Example 1:

Input:

Output:

Explanation: Three 1s become [1,3], two 2s become [2,2], and the single 3 becomes [3,1].

Example 2:

Input:

Output:

Explanation: The two groups of 7s stay separate because the three 8s split them into different runs.

Constraints

  • 0 <= data.length <= 10^5
  • -10^9 <= data[i] <= 10^9
  • The output contains one value-count pair for every maximal run.
  • At most 100 calls are made to encode.
Hints

Loading...
CallReturns
new RunLengthEncoder()null
encode([1,1,1,2,2,3])[1,3,2,2,3,1]

The input contains a run of three 1s, a run of two 2s, and a run of one 3.

Run checks these cases. Submit also runs a larger hidden set.