Problem 338496 · medium · Phase 03 Linear Management & Searching

In-Place Run-Length Encoding

two pointers · in-place · encoding

Given a list of integers nums, compress it in place: every maximal run of equal values is replaced by the value followed by the length of the run, except that runs of length 1 are written as the value alone. Return the length n of the compressed prefix; the contents of nums beyond n do not matter.

Tests use (n := rle_inplace(a := [...]), a[:n])[1] and compare the prefix.

Examples

Input:  nums = [7, 7, 7, 3, 5, 5]
Output: prefix [7, 3, 3, 5, 2]
Explanation: 7 x3 -> 7,3 ; 3 x1 -> 3 ; 5 x2 -> 5,2.

Input:  nums = [1, 2, 3]
Output: prefix [1, 2, 3]

Constraints

  • 0 <= len(nums) <= 10**5
  • Target: O(n) time, O(1) extra space.

Goals

  • Scan a run with a read pointer while a write pointer lags behind
  • Reason about why the writer never overtakes the reader
Starting Python…