Problem 119

Abstract / Summary

Given a list of integers and an integer k, return the k most frequent elements from the list.

Note

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

Python 0119.py

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        # see 118
        prev = [ 1 ]
        for i in range(1, rowIndex + 1):
            row = []
            for j in range(1, i):
                row.append(prev[j - 1] + prev[j])
            prev = [ 1 ] + row + [ 1 ]
        return prev
10 lines | 320 bytes | submitted August 31, 2023 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
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 computes a specific row of Pascal’s Triangle given a zero-based index. It builds each row iteratively, reusing the previously generated row to construct the next one. The method returns the final row as a list of integers.

Algorithmic Flow

The function begins by initializing a list that represents the first row of the triangle, which consists of a single element 1.

prev = [1]

A loop then iterates from 1 up to and including rowIndex. For each iteration i, a new list row is created to hold the interior values of the current row (the values that are not on the edges).

for i in range(1, rowIndex + 1):
    row = []

Inside this loop, a nested loop runs from 1 to i-1. For each position j, the algorithm adds together the two numbers directly above it in the previous row: the element at index j-1 and the element at index j. The sum is appended to row.

    for j in range(1, i):
        row.append(prev[j - 1] + prev[j])

After the interior values are collected, the new row is assembled by placing a leading 1, followed by the computed interior values, and ending with another 1. This new row replaces prev for the next iteration.

    prev = [1] + row + [1]

When the outer loop finishes, prev holds the desired row, which is then returned.

return prev

Edge Cases Handled

When rowIndex is 0, the outer loop does not execute because the range 1 to rowIndex + 1 is empty. The function therefore returns the initially created prev, which correctly represents the first row [1].

When rowIndex is 1, the outer loop runs once. The inner loop’s range 1 to i (where i is 1) yields no iterations, so row remains empty. The construction prev = [1] + row + [1] produces [1, 1], the correct second row.

For larger values of rowIndex, the nested loops correctly generate interior elements by summing adjacent entries from the previous row, ensuring that each row adheres to Pascal’s Triangle properties.

Performance Optimizations

The algorithm reuses a single list (prev) to store the most recent row, avoiding the allocation of a full two-dimensional structure for the entire triangle. By constructing only the needed row, memory consumption is kept minimal.

The inner loop accesses elements of prev directly by index, which is an O(1) operation in Python lists. This direct indexing eliminates the need for additional data structures or look-ups.

The concatenation [1] + row + [1] creates a new list for each iteration, but it does so in a single step, leveraging Python’s efficient list concatenation mechanism. This approach avoids repeated append calls for the edge elements, reducing overhead.

Overall, the method balances clarity with efficient use of list operations, delivering the required row with a compact memory footprint and straightforward computational steps.

written by openai gpt

ELI5 - Simplified Explanation

Imagine building a tall tower out of blocks where each new floor is made by adding together the two blocks directly above it. The code starts with a single block at the very top. Then it looks at that row to figure out what comes next. It creates a new line by placing a one at the start, then it peeks at the row above to add pairs of neighbors together to make the middle numbers, and finally it puts another one at the end. It keeps doing this step by step until it reaches the exact row number requested. Each time a new row is finished, it remembers that row so it can build the next one underneath it, just like building a pyramid.

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 | μ = 7.33 | σ = 0.90

Complexity Analysis

Time: polynomial
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 Rust JS Go Java TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
gaosq0604 Python
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
gaosq0604 Python
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
52 links | 36 authors | 10 languages

Similar Problems

2 similar problems

Solved On The Same Day

27 solutions   August 31, 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