LC441. Arranging Coins¶
Problem Description¶
LeetCode Problem 441: 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.
Clarification¶
- ith row contains i coins
- the last row may or may be incomplete
Assumption¶
- n >= 1
Solution¶
Approach - Brutal Force¶
Follow the problem descriptions, add coins along each row until sum >= n
.
Complexity Analysis¶
- Time complexity: \(O(\sqrt{n})\)
We will go trough \(k\) rows, \(k \leq \sqrt{2n + 0.25}- 0.5\). Refer to the math section below. - Space complexity: \(O(1)\)
Use two variables,sum
andi_row
Approach - Binary Search¶
The problem can be expressed by the following equation:
where \(x\) represents the last incomplete row with range \(0 <= x < (k + 1)\).
Essentially, we are trying to find \(k\) that satisfies:
which means
Then we can use binary search to find \(k\) effectively.
Complexity Analysis¶
- Time complexity: \(O(\log n)\)
Since using the binary search to find \(k\) from space[0, n]
, the time complexity is \(O(\log n)\) - Space complexity: \(O(1)\)
Use 3 variables,left
,mid
,right
.
Approach - Math¶
The equation \(k * (k + 1) \leq 2n\) can be further reduced to:
Since we want the row has full coins, we just find the floor value of \(k\) in the above equation.
Complexity Analysis¶
- Time complexity: \(O(1)\)
Just solve the equation directly. So the time complexity is \(O(1)\). - Space complexity: \(O(1)\)
Comparison of Different Approaches¶
The table below summarize the time complexity and space complexity of different approaches:
Approach | Time Complexity | Space Complexity |
---|---|---|
Approach - Brutal Force | \(O(\sqrt{n})\) | \(O(1)\) |
Approach - Binary Search | \(O(\log n)\) | \(O(1)\) |
Approach - Math | \(O(1)\) | \(O(1)\) |