This problem asks you to return a specific row of Pascal’s Triangle, indexed starting from 0.
Examples:
Input: rowIndex = 3 Output: [1,3,3,1] Input: rowIndex = 0 Output: [1] Input: rowIndex = 1 Output: [1,1]
Problem Understanding
Pascal’s Triangle is built with these rules:
- The first and last element of every row is 1
- Every inner element is the sum of the two numbers directly above it
Example rows:
Row 0: [1] Row 1: [1,1] Row 2: [1,2,1] Row 3: [1,3,3,1] Row 4: [1,4,6,4,1]
But in this problem, you must return only the requested row, not the entire triangle.
Logic Explained in Simple English
There are two main ways to build the requested row:
Approach A (Building full triangle) — Simple but unnecessary
- Build all rows up to rowIndex
- Return the last row
- Works, but wastes time and memory
Approach B (Build only one row) — Better
We can compute the row iteratively:
- Start with
[1] - For each row:
- Append a new value at the end
- Update values from right to left using:
row[j] = row[j] + row[j - 1]
Why right-to-left?
- So updated values don’t overwrite values needed for upcoming calculations
This builds the desired row in-place efficiently.
Approach C (Using combinatorics) — Optimal but less intuitive
Each element in row r at column c is:
C(r, c) = r! / (c! * (r - c)!)
We can compute progressively using multiplication, but Approach B is cleaner for coding rounds.
Step-by-Step Approach (Efficient In-Place)
- Create a list starting with
[1] - Repeat rowIndex times:
- Append
1to expand size - Update inner elements from right to left
- Append
- Return the list
Java Implementation
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> row = new ArrayList<>();
row.add(1);
for (int i = 1; i <= rowIndex; i++) {
row.add(1);
for (int j = i - 1; j > 0; j--) {
row.set(j, row.get(j) + row.get(j - 1));
}
}
return row;
}
}
Dry Run Example
Input:
rowIndex = 4
Start:
row = [1]
Iteration 1:
append 1 → [1,1] (no inner updates)
Iteration 2:
append 1 → [1,1,1] inner j = 1: row[1] = 1 + 1 = 2 → [1,2,1]
Iteration 3:
append 1 → [1,2,1,1] inner j = 2: row[2] = 1 + 2 = 3 inner j = 1: row[1] = 2 + 1 = 3 → [1,3,3,1]
Iteration 4:
append 1 → [1,3,3,1,1] inner j = 3: row[3] = 1 + 3 = 4 inner j = 2: row[2] = 3 + 3 = 6 inner j = 1: row[1] = 3 + 1 = 4 → [1,4,6,4,1]
Final Output:
[1,4,6,4,1]
Time and Space Complexity
Time Complexity
O(n²)
Because each row update touches previous elements
Space Complexity
O(n)
Only the output row is stored
Common Mistakes and How to Avoid Them
Mistake 1: Updating left-to-right
This overwrites needed values — always update right-to-left.
Mistake 2: Building full triangle
Unnecessary memory and computations.
Mistake 3: Using factorials directly
Factorials overflow easily in integer math.
Mistake 4: Off-by-one confusion
Row indexing starts from 0.
Mistake 5: Assuming symmetry means less work
Still must compute middle values properly.
