Pascal’s Triangle – HackerRank Solution

In this post, we will solve Pascal’s Triangle HackerRank Solution. This problem (Pascal’s Triangle) is a part of HackerRank Functional Programming series.

Task

For a given integer K, print the first K rows of Pascal’s Triangle. Print each row with each value separated by a single space. The value at the nth row and rth column of the triangle is equal to n!/(r! * (n – r)!) where indexing starts from 0. These values are the binomial coefficients.

The Pascal Triangle

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
....

Input Format

A single line of input, integer K.

Constraints

  • 2 <= K <= 10

Output Format

Output the first K rows of Pascal’s triangle.

Sample Input

4  

Sample Output

1  
1 1  
1 2 1  
1 3 3 1   

Solution – Pascal’s Triangle – HackerRank Solution

Scala

import java.util.Scanner

object Solution {
  def c(n: Int, k: Int): Int = if (k == 0 || k == n) 1 else c(n - 1, k - 1) + c(n - 1, k)

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val t = sc.nextInt
    sc.close()

    (0 until t).foreach(n => {
      (0 to n).foreach(k => {
        print(s"${c(n, k)} ")
      })
      println()
    })
  }
}

Note: This problem (Pascal’s Triangle) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published.