Decompress Run-Length Encoded List

The given problem deals with run-length encoding, where pairs of elements [freq, val] define how many times the value val should appear consecutively in the decompressed list. Here’s a solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def decompressRLElist(self, nums: List[int]) -> List[int]:
        result = []

        for i in range(0, len(nums), 2):
            freq = nums[i]
            val = nums[i + 1]
            result += [val] * freq

        return result

Explanation

  1. Initialization: We initialize an empty list result to store the decompressed values.

  2. Iterating through Pairs: We iterate through the nums list with a step size of 2 (range(0, len(nums), 2)), so that we can consider pairs of elements [freq, val] at each iteration.

  3. Decompressing Each Pair: Inside the loop, we extract the frequency freq and value val from the current pair. We then create a sublist [val] * freq, which means the value val repeated freq times, and append it to the result list.

  4. Returning the Result: After iterating through all pairs, we return the result list, which represents the decompressed version of the given run-length encoded list.