Expand Count-Value Pairs

EasyArrays & Hashing

Problem

A telemetry link compresses a list of readings as pairs: packed = [count0, value0, count1, value1, …] means value0 repeated count0 times, then value1 repeated count1 times, and so on.

Return the decompressed list. A count may be 0, in which case the pair contributes nothing.

Example 1

Input:
packed = [1, 2, 3, 4]
Output:
[2, 4, 4, 4]

One 2, then three 4s.

Example 2

Input:
packed = [2, 7, 0, 9, 1, -1]
Output:
[7, 7, -1]

The pair (0, 9) produces nothing.

Constraints

  • 2 ≤ packed.length ≤ 200, and the length is even
  • 0 ≤ count ≤ 100
  • -10^4 ≤ value ≤ 10^4

Hint

Show the first hint

Read the input two numbers at a time.

Walkthrough

How to approach it

01Clarify before coding

  • Is the order of pairs preserved? Yes, output follows the pairs in order.
  • Can a count be zero? Yes: skip that pair.
  • Are adjacent pairs with the same value merged? There is nothing to merge: just expand each.

02Brute force

Build the output by concatenating a new list for each pair (out = out + [v] * c).

Cost: Re-copying the growing output at each pair costs O(P · N) for P pairs and N output elements, instead of O(N).

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.