Decompress Run-Length Encoded List (LeetCode 1313): Solution and Explanation

Easy
Array

Read the input two numbers at a time as (count, value) pairs and write each value out count times, in order, to rebuild the original list.

Intuition

Run-length encoding squeezes a list by replacing a run of equal values with the run's length and the value. Decoding is just the reverse: every (length, value) pair turns back into that many copies of the value.

The pairs sit at even and odd positions of nums. Position 2i holds the count and position 2i+1 holds the value, so a loop with a stride of 2 visits each pair exactly once.

Order matters only between pairs, and pairs are already in order, so appending each expanded run to the end of the result produces the right list.

Approach: Expand each pair

  1. Start with an empty result list.
  2. For i = 0, 2, 4, ...: let freq = nums[i] and val = nums[i + 1].
  3. Append val to the result freq times.
  4. Return the result once every pair has been expanded.

Step-by-step example

nums = [1,2,3,4]
  1. Pair 0 is [1,2]: one copy of 2, result = [2].
  2. Pair 1 is [3,4]: three copies of 4, result = [2,4,4,4].
  3. No pairs remain, so return [2,4,4,4].

Code: Python, Java, C++

1class Solution:
2    def decompressRLElist(self, nums: List[int]) -> List[int]:
3        result = []
4        for i in range(0, len(nums), 2):
5            freq, val = nums[i], nums[i + 1]
6            result.extend([val] * freq)
7        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + S)

Each pair is read once (n / 2 pairs) and each output value is written once. S, the output length, is at most 50 * 100 = 5000.

Space

O(S)

Only the output list grows; the loop uses a few integers.

Other approaches

Size first, then fill (time O(n + S), space O(S))

Sum the counts in a first pass, allocate an array of exactly that size, then fill it in a second pass. This avoids list resizing in languages with fixed-size arrays.

List repetition (time O(n + S), space O(S))

In Python, sum([[val] * freq for each pair], []) or a nested comprehension gives the same list in one expression. It is shorter but no faster.

Common mistakes

  • Stepping by 1 instead of 2, which treats every value as a count too.
  • Swapping the roles: the first number of a pair is the count and the second is the value.
  • Allocating an output of size nums.length. The decompressed list is usually longer than the input.

Frequently asked questions

Can a count be zero?

No. Every element is at least 1, so each pair contributes at least one value to the output.

Should equal neighbouring runs be merged?

There is nothing to merge in the output: [2,5,1,5] simply becomes [5,5,5]. The pairs are expanded independently and concatenated.

How big can the output get?

There are at most 50 pairs and each count is at most 100, so the output has at most 5000 values.