Problem 1313

Abstract / Summary

Given a run-length encoded list, expand it into the original list by repeating each number the specified number of times.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1313.py

class Solution:
    def decompressRLElist(self, nums: List[int]) -> List[int]:
        for i in range(0, len(nums), 2):
            freq, val = nums[i], nums[i + 1]
            for j in range(freq):
                yield val
6 lines | 231 bytes | submitted November 16, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 86% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method decompressRLElist. The method receives a list of integers that encodes a run-length encoded (RLE) sequence: each pair of consecutive elements represents a frequency and a value. The method expands the encoding by emitting each value the specified number of times. It does so using a generator, allowing the caller to iterate over the decompressed elements without constructing an intermediate list.

Key Steps

Iterating over the encoded pairs

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

The outer loop steps through the input list with a stride of two, ensuring that each iteration processes exactly one frequency/value pair. By extracting freq and val into local variables, the code avoids repeated indexing inside the inner loop.

Emitting values according to frequency

for j in range(freq):
    yield val

The inner loop runs freq times, yielding the current val on each pass. Because the method uses yield, it produces a lazy sequence rather than materializing the entire decompressed list at once.

Edge Cases Handled

When a frequency is zero, the inner range(freq) produces an empty sequence, so the yield statement is never executed for that pair. This means the method correctly skips values that are meant to appear zero times without raising an error.

If the input list is empty, len(nums) is zero, the outer range produces no indices, and the generator finishes immediately, yielding no elements. The implementation therefore gracefully handles an empty encoding.

The code assumes that the input length is even, as required by the RLE format. When the length is even but the final pair contains a frequency of zero, the generator still terminates correctly after processing all pairs.

Performance Optimizations

The most significant optimization is the use of a generator (yield). By emitting each decompressed element on demand, the method avoids allocating a potentially large list that holds the entire output. This reduces memory consumption, especially for inputs with large frequencies.

Iterating with range(0, len(nums), 2) eliminates the need for additional index calculations or slicing, keeping the loop overhead minimal. Storing freq and val in local variables further reduces attribute lookup costs inside the inner loop.

Overall, the design emphasizes low-memory operation and straightforward iteration, making it well-suited for scenarios where the decompressed sequence is consumed incrementally.

written by openai gpt

ELI5 - Simplified Explanation

Imagine that this code is like a magical recipe for building a line of building blocks. The list of numbers provided is a special set of instructions where every two numbers tell a story. The first number in each pair is the frequency, which tells how many times to pick up a specific block. The second number is the value, which tells which color or shape that block should be.

The first part of the code looks at the list and jumps through it two steps at a time to find these pairs. Once a pair is picked out, the code looks at the frequency and begins a smaller loop. This inner loop performs the action of placing the block down over and over again until the amount matches the frequency. Every single time a block is placed, it is added to a new train of blocks that grows longer and longer. This keeps happening until every pair in the original list has been used to create the final, expanded line of blocks.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.44 | σ = 2.13

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go C Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
Krazune C
lkwq007 Python
muhammadfarhankt Go
sonugiri1043 C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
Krazune C
lkwq007 Python
muhammadfarhankt Go
sonugiri1043 C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
34 links | 21 authors | 10 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 easy 1 medium
5 solutions   November 16, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality