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
Difficulty
and has an acceptance rate of about 68% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Similar Problems
- problem 118: Pascal's Triangle
- problem 2221: Find Triangular Sum of an Array
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
Extra
- 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