Decompress Run-Length Encoded List
Problem
You are given a list nums compressed with run-length encoding. Read it as adjacent pairs [freq, val] = [nums[2i], nums[2i+1]]. Each pair expands to freq copies of val. Concatenate the expansions left to right and return the decompressed list.
nums = [1,2,3,4][2,4,4,4]nums = [1,1,2,3][1,3,3]def decompress(nums):
res = []
for i in range(0, len(nums), 2):
freq, val = nums[i], nums[i + 1]
for _ in range(freq):
res.append(val)
return res
function decompress(nums) {
const res = [];
for (let i = 0; i < nums.length; i += 2) {
const freq = nums[i], val = nums[i + 1];
for (let k = 0; k < freq; k++) {
res.push(val);
}
}
return res;
}
int[] decompress(int[] nums) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length; i += 2) {
int freq = nums[i], val = nums[i + 1];
for (int k = 0; k < freq; k++) {
res.add(val);
}
}
return res.stream().mapToInt(Integer::intValue).toArray();
}
vector<int> decompress(vector<int>& nums) {
vector<int> res;
for (int i = 0; i < (int)nums.size(); i += 2) {
int freq = nums[i], val = nums[i + 1];
for (int k = 0; k < freq; k++) {
res.push_back(val);
}
}
return res;
}
Explanation
Run-length encoding stores a long, repetitive list compactly: instead of writing a value many times, you store the value once together with a count. Decompressing reverses that — we rebuild the full list by expanding each (count, value) pair.
The encoded list packs those pairs flat: positions 0,1 are the first pair, 2,3 the second, and so on. So we walk nums two indices at a time with i += 2, reading freq = nums[i] and val = nums[i + 1].
For each pair we append val exactly freq times to the growing result. Because we process pairs left to right and keep appending, the concatenation order is preserved automatically.
Example: nums = [1,2,3,4]. The pair [1,2] adds one 2; the pair [3,4] adds three 4s. The result is [2,4,4,4].
Total work equals the size of the output, since every appended element corresponds to one decompressed value.