The Wayback Machine - https://web.archive.org/web/20250114123821/https://www.geeksforgeeks.org/find-the-nth-row-in-pascals-triangle/
Open In App

Find the Nth row in Pascal’s Triangle

Last Updated : 07 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a non-negative integer n, the task is to find the nth row of Pascal’s Triangle. 

Note: The row index starts from 0.

Examples:

Input: n = 3
Output: 1 3 3 1
Explanation: The elements in the 3rd row are 1 3 3 1 as shown in Pascal Triangle.

he


Input: n = 0
Output: 1
Explanation: The elements in the 0th row is 1 as shown in Pascal Triangle.

Using Recursion – O(n^2) Time and O(n) Space

The simplest approach to solve the problem is to use Recursion. Find the row of the previous index first using recursion and then calculate the values of the current row with the help of the previous one. Repeat this process up to the nth row. 

C++
// Cpp program to Find the nth row in 
// Pascal’s Triangle using Recursion 
#include <bits/stdc++.h>
using namespace std;

// Function to find the elements 
// of rowIndex in Pascal's Triangle 
vector<int> getRow(int rowIndex) { 
    vector<int> cur; 
    
    // 1st element of every row is 1 
    cur.push_back(1); 
    
    // Check if the row that has to 
    // be returned is the first row 
    if (rowIndex == 0) { 
        return cur; 
    } 
    
    // Generate the previous row 
    vector<int> prev = getRow(rowIndex - 1); 

    for(int i = 1; i < prev.size(); i++) {
        
        // Generate the elements of the current
        // row by the help of the previous row 
        int curr = prev[i - 1] + prev[i]; 
        cur.push_back(curr); 
    } 
    cur.push_back(1); 
    
    // Return the row 
    return cur; 
} 

int main() {
  
    int n = 5; 
    vector<int> arr = getRow(n); 

    for(int i = 0; i < arr.size(); i++) {
        if (i == arr.size() - 1) 
            cout << arr[i]; 
        else
            cout << arr[i] << " ";
    } 
    return 0;
}
Java
// Java program to Find the nth row in 
// Pascal’s Triangle using Recursion 

import java.util.*;

class GfG {
  
    // Function to find the elements 
    // of rowIndex in Pascal's Triangle 
    static List<Integer> getRow(int rowIndex) { 
        List<Integer> cur = new ArrayList<>(); 
        
        // 1st element of every row is 1 
        cur.add(1); 
        
        // Check if the row that has to 
        // be returned is the first row 
        if (rowIndex == 0) { 
            return cur; 
        } 
        
        // Generate the previous row 
        List<Integer> prev = getRow(rowIndex - 1); 
    
        for(int i = 1; i < prev.size(); i++) {
            
            // Generate the elements of the current
            // row by the help of the previous row 
            int curr = prev.get(i - 1) + prev.get(i); 
            cur.add(curr); 
        } 
        cur.add(1); 
        
        // Return the row 
        return cur; 
    } 
    
    public static void main(String[] args) {
        int n = 5; 
        List<Integer> arr = getRow(n); 
    
        for(int i = 0; i < arr.size(); i++) {
            if (i == arr.size() - 1) 
                System.out.print(arr.get(i)); 
            else
                System.out.print(arr.get(i) + " "); 
        } 
    }
}
Python
# Python program to Find the nth row in 
# Pascal’s Triangle using Recursion 

def getRow(rowIndex):
    cur = []
    
    # 1st element of every row is 1 
    cur.append(1)
    
    # Check if the row that has to 
    # be returned is the first row 
    if rowIndex == 0:
        return cur
    
    # Generate the previous row 
    prev = getRow(rowIndex - 1)
    
    for i in range(1, len(prev)):
        # Generate the elements of the current
        # row by the help of the previous row 
        curr = prev[i - 1] + prev[i]
        cur.append(curr)
    cur.append(1)
    
    # Return the row 
    return cur

n = 5
arr = getRow(n)

for i in range(len(arr)):
    if i == len(arr) - 1:
        print(arr[i], end='')
    else:
        print(arr[i], end=' ') 
C#
// C# program to Find the nth row in 
// Pascal’s Triangle using Recursion 

using System;
using System.Collections.Generic;

class GfG {
  
    // Function to find the elements 
    // of rowIndex in Pascal's Triangle 
    static List<int> getRow(int rowIndex) {
        List<int> cur = new List<int>();
        
        // 1st element of every row is 1 
        cur.Add(1);
        
        // Check if the row that has to 
        // be returned is the first row 
        if (rowIndex == 0) {
            return cur;
        }
        
        // Generate the previous row 
        List<int> prev = getRow(rowIndex - 1);
    
        for(int i = 1; i < prev.Count; i++) {
          
            // Generate the elements of the current
            // row by the help of the previous row 
            int curr = prev[i - 1] + prev[i];
            cur.Add(curr);
        }
        cur.Add(1);
        
        // Return the row 
        return cur;
    }
    
    static void Main(string[] args) {
        int n = 5;
        List<int> arr = getRow(n);
    
        for(int i = 0; i < arr.Count; i++) {
            if (i == arr.Count - 1)
                Console.Write(arr[i]);
            else
                Console.Write(arr[i] + " ");
        }
    }
}
JavaScript
// JavaScript program to Find the nth row in 
// Pascal’s Triangle using Recursion 

function getRow(rowIndex) { 
    let cur = []; 
    
    // 1st element of every row is 1 
    cur.push(1); 
    
    // Check if the row that has to 
    // be returned is the first row 
    if (rowIndex === 0) { 
        return cur; 
    } 
    
    // Generate the previous row 
    let prev = getRow(rowIndex - 1); 

    for(let i = 1; i < prev.length; i++) {
        
        // Generate the elements of the current
        // row by the help of the previous row 
        let curr = prev[i - 1] + prev[i]; 
        cur.push(curr); 
    } 
    cur.push(1); 
    
    // Return the row 
    return cur; 
} 


let n = 5; 
let arr = getRow(n); 

for(let i = 0; i < arr.length; i++) {
    if (i === arr.length - 1) 
        process.stdout.write(arr[i].toString());
    else
        process.stdout.write(arr[i] + " "); 
} 

Output
1 5 10 10 5 1

Using Iteration – O(n) Time and O(n) Space

Each element of the nth row in Pascal’s triangle is defined by nCi , where i is the ith element in the row.

pascal-s-triangle
  • Unlike the above approach, we will just generate only the numbers of the nth row.
  • We can observe that the nth row of the Pascal’s triangle consists of following sequence:

nC0,nC1, . . . . . . . . nCn-1, nCn where 0, 1, 2, . . . . . n-1, n are ith element of nth row

  • We can find (i+1)th element of a row using ith element of a row.
  • nCi = n! / (i! * (n-i)!) – ith element of nth row
  • nCi+1 = n! / ((i+1)! * (n-(i+1))! ) – (i+1)th element of nth row
  • Dividing (i+1)th element by ith element will give:
  • nCi+1 / nCi = i! * (n-i)! / (i+1)! * (n-i-1)! – On solving this
  • nCi+1 = nCi * (n-i) / (i+1) –  we get (i+1)th element with the help of ith element
C++
// Cpp program to Find the Nth row in Pascal’s
// Triangle using efficient approach
#include <bits/stdc++.h>
using namespace std;

// Print the N-th row of the Pascal's Triangle
vector<int> generateNthrow(int n) { 
    vector<int> res;
  
    // nC0 = 1
    int prev = 1;
    res.push_back(prev);

    for (int i = 1; i <= n; i++) {
      
        // nCr = (nCr-1 * (n - r + 1))/r 
        int curr = (prev * (n - i + 1)) / i;
        res.push_back(curr);
        prev = curr;
    }
    return res;
}

int main() {
  
    int n = 5;
       vector<int> arr = generateNthrow(n);
      for(int i = 0; i < arr.size(); i++) {
        if (i == arr.size() - 1) 
            cout << arr[i]; 
        else
            cout << arr[i] << " "; 
    } 
    return 0;
}
Java
// Java Program to Find the Nth row in Pascal’s
// Triangle using efficient approach

import java.util.*;

class GfG {
    // Print the N-th row of the Pascal's Triangle
    static List<Integer> generateNthrow(int n) { 
        List<Integer> res = new ArrayList<>();
      
        // nC0 = 1
        int prev = 1;
        res.add(prev);

        for (int i = 1; i <= n; i++) {
          
            // nCr = (nCr-1 * (n - r + 1))/r 
            int curr = (prev * (n - i + 1)) / i;
            res.add(curr);
            prev = curr;
        }
        return res;
    }

    public static void main(String[] args) {
      
        int n = 5;
        List<Integer> arr = generateNthrow(n);
        for(int i = 0; i < arr.size(); i++) {
            if (i == arr.size() - 1) 
                System.out.print(arr.get(i)); 
            else
                System.out.print(arr.get(i) + " "); 
        } 
    }
}
Python
# Python program to Find the Nth row in Pascal’s
# Triangle using an efficient approach

def generateNthrow(n):
    res = []

    # nC0 = 1
    prev = 1
    res.append(prev)

    for i in range(1, n + 1):
      
        # nCr = (nCr-1 * (n - r + 1))/r
        curr = (prev * (n - i + 1)) // i
        res.append(curr)
        prev = curr
    return res


n = 5
arr = generateNthrow(n)
for i in range(len(arr)):
    if i == len(arr) - 1:
        print(arr[i], end='')
    else:
        print(arr[i], end=' ')
C#
// C# program to Find the Nth row in Pascal’s
// Triangle using efficient approach
using System;
using System.Collections.Generic;

class GfG {
  
    // Print the N-th row of the Pascal's Triangle
    static List<int> generateNthrow(int n) {
        List<int> res = new List<int>();

        // nC0 = 1
        int prev = 1;
        res.Add(prev);

        for (int i = 1; i <= n; i++) {
          
            // nCr = (nCr-1 * (n - r + 1))/r
            int curr = (prev * (n - i + 1)) / i;
            res.Add(curr);
            prev = curr;
        }
        return res;
    }

    static void Main() {
        int n = 5;
        List<int> arr = generateNthrow(n);
        for (int i = 0; i < arr.Count; i++) {
            if (i == arr.Count - 1)
                Console.Write(arr[i]);
            else
                Console.Write(arr[i] + " ");
        }
    }
}
JavaScript
// JavaScript program to Find the Nth row in Pascal’s
// Triangle using efficient approach
function generateNthrow(n) { 
    let res = [];
  
    // nC0 = 1
    let prev = 1;
    res.push(prev);

    for (let i = 1; i <= n; i++) {
    
        // nCr = (nCr-1 * (n - r + 1))/r 
        let curr = Math.floor((prev * (n - i + 1)) / i);
        res.push(curr);
        prev = curr;
    }
    return res;
}

let n = 5;
let arr = generateNthrow(n);
let output = '';
for (let i = 0; i < arr.length; i++) {
    if (i == arr.length - 1) 
        output += arr[i];
    else
        output += arr[i] + " "; 
} 
console.log(output);

Output
1 5 10 10 5 1

Unlock your potential with our DSA Self-Paced course, designed to help you master Data Structures and Algorithms at your own pace. In 90 days, you’ll learn the core concepts of DSA, tackle real-world problems, and boost your problem-solving skills, all at a speed that fits your schedule. With comprehensive lessons and practical exercises, this course will set you up for success in technical interviews and beyond.

And here's the challenge – join the Three 90 Challenge! Complete 90% of the course in 90 days, and you’ll earn a 90% refund. It's a great way to stay motivated, track your progress, and reward yourself for your dedication. Start the challenge today, and push your limits to achieve mastery in DSA!


Next Article

Similar Reads

three90RightbarBannerImg