Google questions

Run-Length Encoding

GooglePhone screenMedium

A long list of integers with many equal neighbours is often stored as runs instead of raw values. A run is a pair [value, run_length]: run_length consecutive positions that all hold value. A stored list is an ordered list of runs that covers the whole list, and neighbouring runs never hold the same value.

Implement a class RunLength with methods for working with this format.

Part 1: Encode a vector

Implement encode(vector).

Given a list of integers vector, return its runs in order as a list of [value, run_length] pairs. Every run is maximal, so two neighbouring runs never hold the same value. The empty vector gives [].

  1. Example 1
    init
    []
    operations
    [["encode",[[3,3,3,0,0,0,4,4]]]]
    Output
    [[[3,3],[0,3],[4,2]]]

    Why: The vector starts with three 3s, then three 0s, then two 4s, which gives three runs.

Constraints

  • 0 <= len(vector) <= 10^5
  • -10^9 <= vector[i] <= 10^9
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Run-Length Encoding: Google interview question | LoopCoach