#1936
Add Minimum Number of Rungs
MediumArrayGreedyGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages a greedy approach. We only need to check the distance between the current position and the next rung, adding rungs only when necessary. This minimizes the number of rungs added by always filling the largest gaps first.
⚙️
Algorithm
6 steps- 1Step 1: Initialize current_height to 0 and added_rungs to 0.
- 2Step 2: Iterate through each rung in the rungs array.
- 3Step 3: For each rung, check if the distance from current_height to the rung exceeds dist.
- 4Step 4: If it does, calculate how many rungs need to be added to bridge the gap and update added_rungs and current_height accordingly.
- 5Step 5: If the distance is within the limit, simply update current_height to the rung's height.
- 6Step 6: Return added_rungs after processing all rungs.
solution.py9 lines
1def addRungs(rungs, dist):
2 current_height = 0
3 added_rungs = 0
4 for rung in rungs:
5 if rung - current_height > dist:
6 gap = rung - current_height
7 added_rungs += (gap - 1) // dist
8 current_height = rung
9 return added_rungsℹ
Complexity note: The time complexity is O(n) because we only traverse the rungs array once, making it efficient even for larger inputs.
- 1Always check the distance to the next rung before moving.
- 2Adding rungs at the maximum height possible minimizes the number of rungs needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.