Program to find the nth row of Pascal's Triangle in Python

Pascal's Triangle is a triangular array of numbers where each row represents the binomial coefficients. We need to find the nth row (0-indexed) of this mathematical structure.

Understanding Pascal's Triangle

Pascal's Triangle follows these rules:

  • The top row contains only [1]
  • Each subsequent row starts and ends with 1
  • Each interior number is the sum of the two numbers above it
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Row 0 Row 1 Row 2 Row 3 Row 4

Algorithm Approach

We'll build each row iteratively by adding adjacent elements from the previous row ?

def pascal_triangle_row(n):
    if n == 0:
        return [1]
    if n == 1:
        return [1, 1]
    
    previous_row = [1, 1]
    
    for i in range(2, n + 1):
        current_row = [1]  # Start with 1
        
        # Add adjacent elements from previous row
        for j in range(len(previous_row) - 1):
            current_row.append(previous_row[j] + previous_row[j + 1])
        
        current_row.append(1)  # End with 1
        previous_row = current_row
    
    return previous_row

# Test the function
print(pascal_triangle_row(4))
print(pascal_triangle_row(0))
print(pascal_triangle_row(3))
[1, 4, 6, 4, 1]
[1]
[1, 3, 3, 1]

Using Mathematical Formula

We can also calculate each element directly using the combination formula: C(n,k) = n! / (k! * (n-k)!) ?

def pascal_triangle_formula(n):
    row = []
    
    for k in range(n + 1):
        # Calculate C(n, k) = n! / (k! * (n-k)!)
        value = 1
        for i in range(k):
            value = value * (n - i) // (i + 1)
        row.append(value)
    
    return row

# Test the formula approach
print(pascal_triangle_formula(4))
print(pascal_triangle_formula(5))
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]

Comparison of Methods

Method Time Complexity Space Complexity Best For
Iterative O(n²) O(n) Understanding the pattern
Mathematical O(n) O(n) Direct calculation

Conclusion

Pascal's Triangle can be generated iteratively by summing adjacent elements from the previous row. The mathematical approach using combinations is more efficient for calculating a specific row directly.

Updated on: 2026-03-25T10:57:28+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements