Kundu and Bubble Wrap – HackerRank Solution

In this post, we will solve Kundu and Bubble Wrap HackerRank Solution. This problem (Kundu and Bubble Wrap) is a part of HackerRank Functional Programming series.



Kundu has a Bubble Wrap and like all of us she likes popping it. The Bubble wrap has dimensions NxM, i.e. it has N rows and each row has M cells which has a bubble. Initially all bubbles in filled with air and can be popped.

What Kundu does is randomly picks one cell and tries to pop it, there might be a case that the bubble Kundu selected is already popped. In that case he has to ignore this. Both of these steps take 1 second of time. Tell the total expected number of seconds in which Kundu would be able to pop them all.


Input contains a single line containing two space seperated integers, N M, representing the dimension of Bubble wrap.


Output the required answer in one line. The answer will be considered correct, if its absolute error doesn’t exceed 10-2.


  • 1 ≤ N, M ≤ 1000

Sample Input #00

1 1

Sample Output #00


Sample Input #01

1 2

Sample Output #01


Sample Input #02

=== codingbroz.com_728x90 (#88864) ===
=== codingbroz.com_728x90 (#88864) ===
2 2

Sample Output #02



Test Case #00: There is only one bubble, so he needs only one chance to pop it.
Test Case #01: Expected number of steps of popping two bubbles is 3.
Test Case #02: There are 4 bubbles with equal probability of popping out. Expected number of steps to pop all of them is 8.333333…

Solution – Kundu And Bubble Wrap – HackerRank Solution


import java.util.Scanner

object Solution {
  val count = 100000000000000000L

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

    val m = sc.nextInt
    val n = sc.nextInt


    val q = m * n

    println((1 to q).map(v => calc(v, q)).sum)

  def calc(v: Int, q: Int): Double = {
    val pNo = (q - v).toDouble / q
    (1 - math.pow(pNo, count)) / (1 - pNo)

Note: This problem (Kundu and Bubble Wrap) 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.