You are given a list nums
where each pair of elements in the list represent [frequency, value]
sequence. Your task is to return the decompressed version of the list where each value
appears frequency
times consecutively in the list.
Example:
nums = [1,2,3,4]
[2,4,4,4]
nums
?
nums
is guaranteed to be even, and it’s between 2 and 100.nums
list:
extend
method to add the value
repeated frequency
times to the resulting list.f
, we add f
elements to the result. In the worst case, where the total number of elements added is proportional to the sum of frequencies, time complexity is O(n), where n
is the sum of all frequencies in the input list.n
is the length of the output list.def decompressRLElist(nums):
decompressed_list = []
for i in range(0, len(nums), 2):
frequency = nums[i]
value = nums[i + 1]
decompressed_list.extend([value] * frequency)
return decompressed_list
Let’s test the implementation with one of the provided examples:
Example 1:
nums = [1, 2, 3, 4]
[2, 4, 4, 4]
Explanation:
[1, 2]
: This means 2
appears 1
time.[3, 4]
: This means 4
appears 3
times.So, the decompressed list is [2, 4, 4, 4]
.
Using the provided implementation, this would effectively solve the given problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?