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.

Input: n = 5
Output: 2
Explanation: After arranging 5 coins, 1st row will have 1 coin, 2nd row will 2 coins, and 3rd row will have 2 coins. Since the 3rd row is incomplete, we return 2. Example 1
Input: n = 8
Output: 3
Explanation: Because the 4th row is incomplete, we return 3. Example 2
Constraints:

Contents

As per the problem statement, we have n coins and we have to arrange them in rows, like 1 coin in 1st row and 2 coins in 2nd row and so on. So, one possible solution we can apply is, we start by subtracting number of coins needed for that row from total number of coins n and count how many rows we can built, for example say n=10.

In this solution, we have to go row by row and the time complexity is going to be ~O(n), but there is a O(log n) sulution using Binary Search algorithm.

In this approach, we will math formula that the sum of elements from 1....n, sum of integers formula 1+2+3+4... sum = n * (n+1) _____________ 2 Then, we apply binary search with the range of numbers 1....n. First we will initialize two pointers left =1 and right =n and then using a while loop, compute the middle index and compute the sum using above formula, that gives sum between 1...mid , based on the value of sum, we can draw three conclusions.

Finally, we will return right index as answer, since right index will be placed at the upper boundary where we have utilized all coins and built upto right number of rows.

public class ArrangeCoins { static int arrangeCoins(int n) { // 1, 2, 3, 4, --- sum formula sum = n(n+1) /2 int left = 1; int right= n; while(left<=right) { int mid = left + (right - left) /2; long sum = (long)mid * (mid+1) /2; if(sum==n) { return mid; } else if (sum>n) { right = mid-1; } else { left = mid+1; } } return right; } public static void main(String[] args) { System.out.println(arrangeCoins(5)); System.out.println(arrangeCoins(8)); System.out.println(arrangeCoins(1804289383)); } }
Complexity Analysis:

Time complexity: Above code runs in O(log n) time where n is the input number.
Space complexity: O(1).

Above implementations source code can be found at GitHub link for Java code