15% off all plans & roadmaps Use code

See plans

Furthest Building You Can Reach

Updated

TL;DR: You walk right and pay for each climb with one ladder or with bricks equal to the height gap. Give ladders to the biggest climbs by keeping them in a min-heap, and when the heap overflows, pay bricks for the smallest climb in it.

Problem

You get a list of building heights, some bricks, and some ladders. You start on building 0 and move to the next building one step at a time.

A move from building i to building i+1 (0-indexed) follows two rules.

  • If the current building is at least as tall as the next one, the move costs nothing.
  • If the next building is taller, you pay with one ladder or with bricks equal to the height difference.

Return the furthest building index you can reach when you use the ladders and bricks optimally.

Example 1

Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output: 4
Explanation:
- Go to building 1 for free, since 4 >= 2.
- Go to building 2 with 5 bricks, because 2 < 7.
- Go to building 3 for free, since 7 >= 6.
- Go to building 4 with your only ladder, because 6 < 9.

You cannot go past building 4, since you have no bricks or ladders left.

Example 2

Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
Output: 7

Example 3

Input: heights = [14,3,19,3], bricks = 17, ladders = 0
Output: 3

Constraints

  • 1 <= heights.length <= 10^5
  • 1 <= heights[i] <= 10^6
  • 0 <= bricks <= 10^9
  • 0 <= ladders <= heights.length

Constraints that matter

  • heights.length up to 10^5 rules out trying every split of climbs between ladders and bricks, because that search is exponential.
  • bricks up to 10^9 rules out a DP table indexed by the bricks left, so the state has to come from the climbs themselves.
  • ladders can be as large as heights.length, so the heap can hold up to n values and each heap operation costs O(log n) in the worst case.
  • heights up to 10^6 keeps every difference well inside a 32-bit int, so Java, C++, C# and Go need no wider type.

View on LeetCode

Hints

Hint 1

Every climb needs exactly one payment.

Hint 2

Try both payments at every climb and keep the best reach.

Solution

Intuition

Every climb needs exactly one payment. A ladder covers any height gap, and bricks cover only the size of the gap. So a ladder is worth the most on the biggest climbs. The problem becomes choosing which climbs get ladders, and a priority queue is the usual tool for a greedy choice like this.

Picture a fixed number of golden tickets handed out to the tallest hills on a hike. The heap is the set of hills holding tickets, and its smallest entry is the cheapest hill to hand a ticket back to.

What to notice: at step i you cannot know whether a larger climb comes later. So you decide tentatively. Give each climb a ladder when you meet it, and keep those climbs in a min-heap that holds at most as many entries as you have ladders. When the heap overflows, its smallest climb gives up its ladder and pays bricks.

Why this works: suppose a ladder covers a small climb x while a larger climb y pays bricks. Swapping the two never costs more bricks, because you pay x bricks instead of y. So the ladder-covered set should always be the largest climbs seen so far. The heap holds exactly that set, and its smallest element is the cheapest climb to demote.

Watch the pattern animation

Worked example

Input: heights = [1, 1, 1, 1], bricks = 0, ladders = 0
Output: 3
Explanation: Every building is the same height, so no move is a climb. You need no bricks and no ladders, and you reach the last building, index 3.

Approach 1: Brute force recursion

Try both payments at every climb and keep the best reach. At a climb you can spend a ladder or spend bricks, and each choice leads to its own remaining path. The beginner version explores every such path and returns the largest index any path reaches. Nothing is cached, so the same states are solved again and again.

Steps

  1. Start a recursive call at index 0 with all the bricks and all the ladders.
  2. If the next building is not taller, move on for free and recurse from there.
  3. If the next building is taller and a ladder is left, recurse with one fewer ladder.
  4. If the next building is taller and you have enough bricks, recurse with the difference subtracted from bricks.
  5. Return the largest result you found, or the current index if neither payment is possible.

Dry run

The example heights = [1, 1, 1, 1] with 0 bricks and 0 ladders has no climb, so the recursion never branches. The call reach(0, 0, 0) calls reach(1, 0, 0), which calls reach(2, 0, 0), which calls reach(3, 0, 0). Index 3 is the last building, so that call returns 3, and every caller passes 3 back up. The output is 3.

Complexity

TimeO(2^n)
SpaceO(n)

Let n be the number of buildings. Each climb makes two recursive calls, and each free move makes one. A path has at most n - 1 moves, so there are up to 2^(n-1) root-to-leaf paths when every move is a climb and resources never run out. The recursion depth is at most n, which gives O(n) stack space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
        n = len(heights)

        def reach(i: int, b: int, l: int) -> int:
            # Furthest index reachable from building i with b bricks and l ladders left
            if i == n - 1:
                return i
            diff = heights[i + 1] - heights[i]
            if diff <= 0:
                return reach(i + 1, b, l)
            best = i  # staying on building i is always possible
            if l > 0:
                best = max(best, reach(i + 1, b, l - 1))
            if b >= diff:
                best = max(best, reach(i + 1, b - diff, l))
            return best

        return reach(0, bricks, ladders)

The Scheduling / Minimum Cost (Greedy with Priority Queue) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Scheduling / Minimum Cost (Greedy with Priority Queue)

Part of Heap (Priority Queue) Patterns

Approach 2: One-pass min-heapOptimalScheduling / Minimum Cost (Greedy with Priority Queue)

What is slow: the brute force branches on every climb, so it tests every way to split the climbs between ladders and bricks. Most of those splits are worse than one simple rule. The insight that fixes it: the climbs that hold ladders should always be the largest ones seen so far. A min-heap of at most ladders entries tracks that set, and one pass over the buildings is enough.

Why it is correct. The heap always holds the k largest climbs seen so far, where k is the number of ladders. If a smaller climb held a ladder while a larger one paid bricks, swapping them never costs more bricks. So demoting the heap's minimum is the cheapest payment whenever the heap overflows.

Steps

  1. Create an empty min-heap that will hold the climbs covered by ladders.
  2. Walk i from 0 to n - 2 and compute diff = heights[i+1] - heights[i].
  3. If diff is 0 or negative, skip it, because that move is free.
  4. Otherwise push diff onto the heap.
  5. If the heap holds more climbs than there are ladders, pop the smallest one and subtract it from bricks.
  6. If bricks is now negative, return i, because building i+1 is out of reach.
  7. If the loop finishes, return n - 1.

Dry run

The example heights = [1, 1, 1, 1] with 0 bricks and 0 ladders has no climbs, so the heap never gets a value.

StepiHeightsdiffActionHeapBricksResult
101 to 10free moveempty0continue
211 to 10free moveempty0continue
321 to 10free moveempty0continue
4endloop donen/areturn n - 1empty0return 3

The output is 3.

The example has no climbs, so it does not test the heap. Example 1 from the statement, with 5 bricks and 1 ladder, does. At i = 1 the climb 5 enters the heap, which holds one value and fits the single ladder. At i = 3 the climb 3 enters, so the heap holds the values 3 and 5 and overflows. Popping 3 leaves bricks at 2. At i = 4 the climb 5 enters, so the heap holds 5 and 5. Popping one 5 drops bricks to -3, so the function returns 4.

Complexity

TimeO(n log L)
SpaceO(L)

Let n be the number of buildings and L the number of ladders. The loop runs n - 1 times, and each climb does one push and at most one pop. The heap never holds more than L + 1 values at once, so each push or pop costs O(log L), and when L is 0 the heap work is constant, so the total is O(n log L). The heap stores at most L + 1 values, so the space is O(L).

PythonTested in our runner

from typing import List, Optional
import heapq

class Solution:
    def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
        climbs = []  # min-heap of the climbs currently covered by ladders
        for i in range(len(heights) - 1):
            diff = heights[i + 1] - heights[i]
            if diff <= 0:
                continue  # a free move needs no ladder or bricks
            heapq.heappush(climbs, diff)
            if len(climbs) > ladders:
                # The smallest climb gives up its ladder and pays bricks
                bricks -= heapq.heappop(climbs)
                if bricks < 0:
                    return i
        return len(heights) - 1

Common mistakes

  • Subtracting diff from bricks for every climb, including climbs that still hold a ladder. Only the climb popped from the heap pays bricks. Subtract the popped value and nothing else.
  • Using a max-heap, so pop removes the largest climb. The climb to demote is the smallest one, so the heap must be a min-heap.
  • Pushing descents into the heap. A negative diff pops first and adds bricks, so you reach buildings you cannot reach. Skip every diff that is 0 or below.
  • Returning i + 1 when bricks go negative. The move from i to i+1 is the one you cannot pay for, so the furthest reachable index is i.
  • Looping to heights.length and reading heights[i + 1] past the end. Stop the loop at n - 2, so the last comparison uses index n - 1.
  • Building a DP table indexed by bricks left. Bricks can be 10^9, so the table is far too large. Track the climbs in the heap instead.

Edge cases

  • A single building, heights = [5]: the loop never runs, so return 0.
  • Heights that never rise, such as [9, 7, 7, 1] with 0 bricks and 0 ladders: every move is free, so return the last index, 3.
  • Zero bricks and zero ladders with a first climb, such as [1, 2]: the climb cannot be paid, so return 0.
  • Bricks exactly equal to a climb, such as [1, 3] with 2 bricks and 0 ladders: bricks drop to 0, which is not negative, so return 1.
  • Ladders at least as many as the climbs, such as [1, 5, 2, 9] with 3 ladders: the heap never overflows, so return 3.
  • Maximum sizes: 10^5 buildings with heights up to 10^6 and bricks up to 10^9. Differences fit in a 32-bit int, and the heap never exceeds L + 1 values.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Furthest Building You Can Reach, with how to answer them.

Unlock the follow-ups

Furthest Building You Can Reach FAQ

What is the time complexity of Furthest Building You Can Reach?

The heap solution runs in O(n log L) time, where n is the number of buildings and L is the number of ladders. The brute force recursion runs in O(2^n) time. The heap approach is the one to write in an interview.

Why use a min-heap for Furthest Building You Can Reach?

The min-heap holds the climbs that currently have ladders. When it overflows, the smallest climb is the cheapest one to pay with bricks, and a heap returns that minimum in O(log L) time.

Can Furthest Building You Can Reach be solved in O(1) extra space?

No, not with the heap method. The heap stores up to L climbs at once, and L can be close to n. The single pass keeps the work simple, but the heap is what needs the space.

Why not use dynamic programming for Furthest Building You Can Reach?

A DP indexed by bricks left needs a table as large as bricks, which can be 10^9. A DP indexed by ladders used works, with the most bricks left as the value, but it takes O(n * L) time, which is about 10^10 when L is near n.

Does Furthest Building You Can Reach need sorting?

Not for the main solution. The climbs must be handled in the order you meet them, so sorting them up front does not give a valid answer by itself. Sorting only helps in the binary search variant covered in the follow-ups.

Asked at

See which companies ask this — Pro

Practise it