[Solved] You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build.

Table of Contents

Question

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will build.

Example 1:

arrangecoins1 grid
Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.

Example 2:

arrangecoins2 grid
Input: n = 8
Output: 3
Explanation: Because the 4th row is incomplete, we return 3.

Constraints:

  • 1 <= n <= 231 - 1

Python Solution

class Solution:
    def arrangeCoins(self, n: int) -> int:
        if n==1:
            return 1
        l=0
        r=n//2 + 1
        while l<=r:
            m = l+(r-l)//2
            x = (m*(m+1)//2)
            if x==n:
                return(m)
            elif x<n:
                l = m+1
            else:
                r=m-1
        return(l-1)

Leave a Reply

Your email address will not be published. Required fields are marked *