Decompress Run-Length Encoded List - Problem

We are given a list nums of integers representing a list compressed with run-length encoding.

Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.

Return the decompressed list.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4]
Output: [2,4,4,4]
💡 Note: First pair [1,2]: frequency 1, value 2 → add 2 once. Second pair [3,4]: frequency 3, value 4 → add 4 three times. Result: [2,4,4,4]
Example 2 — Multiple Pairs
$ Input: nums = [1,1,2,3]
Output: [1,3,3]
💡 Note: First pair [1,1]: frequency 1, value 1 → add 1 once. Second pair [2,3]: frequency 2, value 3 → add 3 twice. Result: [1,3,3]
Example 3 — Zero Frequency
$ Input: nums = [2,1,3,2]
Output: [1,1,2,2,2]
💡 Note: First pair [2,1]: frequency 2, value 1 → add 1 twice. Second pair [3,2]: frequency 3, value 2 → add 2 three times. Result: [1,1,2,2,2]

Constraints

  • 2 ≤ nums.length ≤ 100
  • nums.length % 2 == 0
  • 1 ≤ nums[2 * i] ≤ 100
  • 1 ≤ nums[2 * i + 1] ≤ 100

Visualization

Tap to expand
Run-Length Encoding Decompression INPUT nums = [1, 2, 3, 4] 1 2 3 4 i=0 i=1 i=2 i=3 Pair 1 [freq=1, val=2] Pair 2 [freq=3, val=4] Each pair defines: freq = how many times val = which value to repeat [nums[2i], nums[2i+1]] = [freq, val] for i = 0, 1, 2, ... ALGORITHM STEPS 1 Calculate Total Size Sum all freq values: total = 1 + 3 = 4 2 Pre-allocate Result Create array of size 4 result = [_, _, _, _] 3 Process Pair 1 [1, 2]: add 2 once result = [2, _, _, _] 4 Process Pair 2 [3, 4]: add 4 three times result = [2, 4, 4, 4] Single Pass Filling: 2 4 4 4 P1 P2 x3 FINAL RESULT Decompressed List: 2 4 4 4 [0] [1] [2] [3] Output: [2, 4, 4, 4] OK - Verified! Length = 4, correct values Breakdown: Pair [1,2] --> [2] Pair [3,4] --> [4,4,4] Combined --> [2,4,4,4] Key Insight: Pre-allocation Strategy: First pass calculates total output size by summing all frequency values. This avoids expensive array resizing operations. Second pass fills the pre-allocated array in O(n) time where n = sum of all frequencies. Space complexity is O(1) extra (output excluded). TutorialsPoint - Decompress Run-Length Encoded List | Single Pass with Pre-allocation
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
25.0K Views
Medium Frequency
~10 min Avg. Time
850 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