Add Minimum Number of Rungs - Problem

You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.

You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there.

Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.

Input & Output

Example 1 — Basic Gap Filling
$ Input: rungs = [1,3,5,10], dist = 2
Output: 2
💡 Note: Gap from 0→1 is 1 (≤2, ok). Gap from 1→3 is 2 (≤2, ok). Gap from 3→5 is 2 (≤2, ok). Gap from 5→10 is 5 (>2), need (5-1)/2 = 2 rungs at heights 7 and 9.
Example 2 — Multiple Small Gaps
$ Input: rungs = [3,6,8,10], dist = 3
Output: 0
💡 Note: Gap 0→3 is 3 (≤3, ok). Gap 3→6 is 3 (≤3, ok). Gap 6→8 is 2 (≤3, ok). Gap 8→10 is 2 (≤3, ok). No additional rungs needed.
Example 3 — Large Initial Gap
$ Input: rungs = [3,4,6,7], dist = 2
Output: 1
💡 Note: Gap 0→3 is 3 (>2), need (3-1)/2 = 1 rung. All other gaps are ≤2. Total: 1 rung.

Constraints

  • 1 ≤ rungs.length ≤ 105
  • 1 ≤ rungs[i] ≤ 109
  • 1 ≤ dist ≤ 109
  • rungs is strictly increasing

Visualization

Tap to expand
Add Minimum Number of Rungs INPUT h=1 h=3 h=5 h=10 h=0 rungs = [1,3,5,10] dist = 2 ALGORITHM STEPS 1 Check gap 0 to 1 Gap=1, dist=2: OK 2 Check gap 1 to 3 Gap=2, dist=2: OK 3 Check gap 3 to 5 Gap=2, dist=2: OK 4 Check gap 5 to 10 Gap=5, dist=2: NEED RUNGS! Formula: rungs = (gap-1) / dist = (5-1) / 2 = 2 Gap of 5 needs: h=7 and h=9 (new rungs) 5 --> 7 --> 9 --> 10 FINAL RESULT 1 3 5 7 NEW 9 NEW 10 0 OUTPUT 2 Key Insight: For each gap larger than dist, calculate minimum rungs needed: ceil((gap - 1) / dist) or (gap - 1) / dist using integer division. Greedy approach works because we want evenly spaced rungs to minimize count. Each new rung should be exactly dist apart. Time: O(n) | Space: O(1) where n = number of rungs TutorialsPoint - Add Minimum Number of Rungs | Greedy - Optimal Gap Filling
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
26.3K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen