Decompress Run-Length Encoded List - Problem

Run-Length Encoding (RLE) is a simple compression technique used in data storage and transmission. In this problem, you're given a compressed array and need to decompress it back to its original form.

You are given an array nums where each pair of adjacent elements represents compressed data:

  • Format: [frequency, value, frequency, value, ...]
  • Each pair [nums[2*i], nums[2*i+1]] means: repeat nums[2*i+1] exactly nums[2*i] times

Goal: Decompress the array by expanding each [frequency, value] pair into a sequence of repeated values, then concatenate all sequences from left to right.

Example: [1,2,3,4][2,4,4,4]
Because: 1×2 + 3×4 = [2] + [4,4,4] = [2,4,4,4]

Input & Output

example_1.py — Basic Case
$ Input: nums = [1,2,3,4]
Output: [2,4,4,4]
💡 Note: The pairs are [1,2] and [3,4]. This means take value 2 once and value 4 three times, resulting in [2,4,4,4].
example_2.py — Multiple Pairs
$ Input: nums = [1,1,2,3,3,2]
Output: [1,3,3,2,2,2]
💡 Note: The pairs are [1,1], [2,3], and [3,2]. This expands to [1] + [3,3] + [2,2,2] = [1,3,3,2,2,2].
example_3.py — Edge Case
$ Input: nums = [2,5]
Output: [5,5]
💡 Note: Single pair [2,5] means take value 5 twice, resulting in [5,5].

Constraints

  • 2 <= nums.length <= 100
  • nums.length % 2 == 0
  • 1 <= nums[2*i] <= 100
  • 0 <= nums[2*i+1] <= 100
  • The input array always has even length

Visualization

Tap to expand
🎵 Run-Length Decompression Like MusicCompressed: [1, ♪, 3, ♫]1×♪3×♫Expand each pairDecompressed Result:[♪, ♫, ♫, ♫]Algorithm Steps:1. Read pairs: [freq₁, val₁], [freq₂, val₂]2. For each pair (freq, val): • Add val to result freq times3. Concatenate all resultsExample: [1,2,3,4] → [2,4,4,4]• Pair [1,2]: add 2 once → [2]• Pair [3,4]: add 4 thrice → [4,4,4]• Result: [2] + [4,4,4] = [2,4,4,4]Time & Space ComplexityTime: O(n + m) where n = input size, m = output sizeSpace: O(m) for the output array• We process each input element once: O(n)• We create exactly m output elements: O(m)• No additional space beyond output needed
Understanding the Visualization
1
Read Compressed Format
Parse input as [frequency, note, frequency, note, ...]
2
Process Each Pair
For each [freq, note], add note to result freq times
3
Build Final Sequence
Concatenate all expanded notes into final melody
4
Return Decompressed
Output the complete expanded sequence
Key Takeaway
🎯 Key Insight: This problem requires direct expansion without complex data structures - just process each frequency-value pair and build the result incrementally.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
58.0K Views
Medium Frequency
~8 min Avg. Time
2.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen