Add Minimum Number of Rungs — LeetCode 1936 Python Solution

MediumGreedyArray
Problem
#1936
Pattern
Greedy
Reading time
2 min

The 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.

Example

Input
rungs = [1,3,5,10], dist = 2
Output
2
Explanation
You currently cannot reach the last rung.

Python solution

Python
class Solution:
    def addRungs(self, rungs: List[int], dist: int) -> int:
        rungs = [0] + rungs
        return sum((b - a - 1) // dist for a, b in pairwise(rungs))

Complexity

MeasureComplexity
TimeO(n), where n is the length of `rungs`
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1936. Add Minimum Number of Rungs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1936. Add Minimum Number of Rungs?
LeetCode 1936. Add Minimum Number of Rungs is rated Medium on LeetCode.
What is the time complexity of LeetCode 1936. Add Minimum Number of Rungs?
The Python solution on this page runs in O(n), where n is the length of `rungs`.
What is the space complexity of LeetCode 1936. Add Minimum Number of Rungs?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1936. Add Minimum Number of Rungs cover?
LeetCode 1936. Add Minimum Number of Rungs is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview