↓Skip to main content
  1. LeetCode/

LeetCode 118: Pascal's Triangle

·1 min· ·
LeetCode Easy Array Dynamic-Programming
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-16

  • Submissions: Accepted ×6

Approach
#

Row i has i + 1 numbers with 1 at both ends, and inner cells are row[j] = prev[j - 1] + prev[j] (Linear DP Template 1). Create rows of 1s first, then fill the middle.

My Solution
#

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        rows = [[1] * (i + 1) for i in range(numRows)]
        for i in range(2, numRows):
            for j in range(1, i):
                rows[i][j] = rows[i - 1][j - 1] + rows[i - 1][j]
        return rows

Complexity
#

Time O(n²), space O(n²) (output).

Mistakes to Avoid
#

  • Row i has i + 1 numbers, counting from 0.

Interview Explanation
#

Each row has 1s at the ends and each inner cell sums the two cells above, so I create rows of 1s and fill the middle. Time O(n²).

Related

LeetCode 119: Pascal's Triangle II
·2 mins
LeetCode Easy Array Dynamic-Programming
LeetCode 119 note: only row rowIndex is needed; update a 1D array from right to left for O(k) space
LeetCode 136: Single Number
·1 min
LeetCode Easy Array Bit-Manipulation
LeetCode 136 note: x ^ x = 0 and x ^ 0 = x, so XOR everything; pairs cancel and the single number remains
LeetCode 108: Convert Sorted Array to Binary Search Tree
·1 min
LeetCode Easy Array Divide-and-Conquer Tree Binary-Search-Tree
LeetCode 108 note: the middle element becomes the root and each half recurses; the halves differ by at most one, so the tree is balanced
LeetCode 27: Remove Element
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 27 note: the write pointer copies only values not equal to val, returning how many were written
LeetCode 35: Search Insert Position
·2 mins
LeetCode Easy Array Binary-Search
LeetCode 35 note: find the first position >= target (lower bound); a half-open [l, r) needs r = mid, not r = mid - 1
LeetCode 66: Plus One
·2 mins
LeetCode Easy Array Math
LeetCode 66 note: add one from the last digit, turning 9s into 0s while carrying, and prepend 1 when every digit was 9