#1313
Decompress Run-Length Encoded List
EasyArrayArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single pass through the input list while calculating the total size of the decompressed list first, then constructs it in a second pass. This avoids unnecessary repeated appending and improves efficiency.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total size of the decompressed list by summing all frequencies.
- 2Step 2: Create an array of that size.
- 3Step 3: Fill the array by iterating through the input list, placing each value at the correct indices based on its frequency.
solution.py12 lines
1# Full working Python code
2
3def decompressRLElist(nums):
4 total_length = sum(nums[i] for i in range(0, len(nums), 2))
5 decompressed = [0] * total_length
6 index = 0
7 for i in range(0, len(nums), 2):
8 freq = nums[i]
9 val = nums[i + 1]
10 decompressed[index:index + freq] = [val] * freq
11 index += freq
12 return decompressedℹ
Complexity note: The time complexity is O(n) because we traverse the input list twice, and the space complexity is O(n) due to the storage of the decompressed list.
- 1Understanding run-length encoding helps in visualizing the problem.
- 2Recognizing the need for efficient list construction can lead to better solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.