Furthest Building You Can Reach solution explained

Furthest Building You Can Reach asks how far along a row of buildings you can get, moving one building at a time, when every climb to a taller building costs either its height difference in bricks or one ladder. Walk forward, push each climb onto a min-heap, and whenever the heap holds more climbs than you have ladders, pay for the smallest one with bricks. The first time bricks go negative, the current building is the answer. That is O(n log L) for L ladders.

By Published 9 min read

The problem, in plain terms

You stand on building 0 of a row and want to move right, one building at a time. Stepping to a building that is the same height or lower is free. Stepping up to a taller one costs either exactly the height difference in bricks or a single ladder, which covers any climb. Bricks and ladders are used up. Given the heights, the bricks and the ladders, return the index of the furthest building you can reach by spending them wisely.

Skyline A: heights [3, 7, 5, 6, 10, 9, 12], bricks 5, ladders 1
  climbs on the way: 0->1 up 4, 2->3 up 1, 3->4 up 4, 5->6 up 3
  best plan: ladder on one climb of 4, bricks on 1 and the other 4 (5 bricks)
  the climb of 3 into building 6 cannot be paid for      answer: 5

Skyline B: heights [2, 7, 8, 9], bricks 5, ladders 1
  climbs: 5, 1, 1
  spend bricks first: 5 bricks on the 5, ladder on a 1, stuck    reaches 2
  ladder on the 5, bricks on the two 1s                          reaches 3
Two skylines, made up for this page

Skyline B is the counterexample to the obvious rule of spending bricks while you can and switching to ladders when bricks run short. The ladder belonged on the climb of 5, but you only know that in hindsight. The heap solution lets you make that decision in hindsight, cheaply.

Good questions to ask first: can bricks or ladders be zero? Is the answer an index (yes here) or a count of buildings? Are heights always positive integers? The answers do not change the algorithm, but they tell the interviewer you are thinking about the edges.

What interviewers look for

This problem tests whether you can turn "I would have chosen differently if I had known" into a data structure. A strong answer names the greedy invariant (ladders always sit on the largest climbs so far), uses a heap to keep it, and explains why the first failure is final. Many candidates reach for dynamic programming over (index, bricks, ladders), which is far too large.

Brute force: try both resources on every climb

At each climb, branch: pay with bricks if you have enough, or use a ladder if you have one. Track the furthest index any branch reaches. That is up to 2 to the power of the number of climbs, so it only works on tiny inputs, but it is the honest reference for testing.

def furthest_slow(heights, bricks, ladders):
    def go(i, b, l):
        while i + 1 < len(heights) and heights[i + 1] <= heights[i]:
            i += 1  # free steps
        if i + 1 == len(heights):
            return i
        rise = heights[i + 1] - heights[i]
        best = i
        if b >= rise:
            best = max(best, go(i + 1, b - rise, l))
        if l > 0:
            best = max(best, go(i + 1, b, l - 1))
        return best

    return go(0, bricks, ladders)
Python: exhaustive search over brick-or-ladder choices. Exponential time.

Optimal approach: a min-heap of ladder climbs

Walk left to right. For every climb, tentatively give it a ladder by pushing its size onto a min-heap. If the heap now holds more climbs than you have ladders, one of them must be paid with bricks, and the cheapest one to pay for is the smallest, which sits at the top of the heap. Pop it and subtract it from bricks. If bricks drop below zero, you cannot take this step, so the answer is the building you are standing on.

import heapq


def furthest(heights, bricks, ladders):
    on_ladders = []  # sizes of climbs assigned to ladders
    for i in range(len(heights) - 1):
        rise = heights[i + 1] - heights[i]
        if rise <= 0:
            continue
        heapq.heappush(on_ladders, rise)
        if len(on_ladders) > ladders:
            bricks -= heapq.heappop(on_ladders)  # smallest climb goes to bricks
            if bricks < 0:
                return i
    return len(heights) - 1
Python: heapq holding the climbs that currently use ladders. O(n log L) time.

Why stopping at the first failure is right: at that moment the heap holds the L largest climbs so far on ladders, and every other climb so far is on bricks. That assignment uses the fewest bricks possible for reaching index i + 1. If even that is too many, no plan reaches i + 1, and therefore none reaches anything beyond it.

With zero ladders, the push is followed immediately by a pop, so the code naturally pays every climb with bricks. The C++ version is the same loop with a priority_queue flipped into a min-heap.

#include <functional>
#include <queue>
#include <vector>

int furthestBuilding(const std::vector<int>& heights, long long bricks, int ladders) {
    std::priority_queue<int, std::vector<int>, std::greater<int>> onLadders;
    for (int i = 0; i + 1 < (int)heights.size(); ++i) {
        int rise = heights[i + 1] - heights[i];
        if (rise <= 0) continue;
        onLadders.push(rise);
        if ((int)onLadders.size() > ladders) {
            bricks -= onLadders.top();
            onLadders.pop();
            if (bricks < 0) return i;
        }
    }
    return (int)heights.size() - 1;
}
C++17: min-heap via std::greater

Another route: binary search on the answer

Reachability is monotonic: if you can reach building t, you can reach every building before it. And you can reach t exactly when the climbs up to t, minus the L largest of them, total at most the bricks. So binary search on t, and for each guess sort the climbs (or use a selection algorithm) to check it. It is slower than the heap but a perfectly good answer to give if the heap idea does not come to you first.

def furthest_bsearch(heights, bricks, ladders):
    def can_reach(t):
        rises = sorted(max(0, heights[j + 1] - heights[j]) for j in range(t))
        paid = rises[:max(0, len(rises) - ladders)]  # all but the largest L
        return sum(paid) <= bricks

    lo, hi = 0, len(heights) - 1
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if can_reach(mid):
            lo = mid
        else:
            hi = mid - 1
    return lo
Python: binary search with a sort-based check. O(n log² n) time.

Complexity summary

n buildings, L ladders
ApproachTimeExtra memoryNote
Brick-or-ladder searchExponentialO(n) stackReference only
DP over (index, bricks used)O(n × bricks)LargeBricks can be huge, so impractical
Binary search plus sortO(n log² n)O(n)Easy to prove, a little slower
Min-heap of ladder climbsO(n log L)O(L)Expected answer
n buildings, L ladders. Scroll sideways on a small screen.

Edge cases to try

  • A single building: the answer is 0.
  • Heights that never rise: you reach the last building with nothing spent.
  • No ladders: every climb is paid in bricks, in order.
  • No bricks: you can take exactly as many climbs as you have ladders.
  • More ladders than climbs: you always reach the end.
  • A climb that exactly uses up the remaining bricks: allowed, since bricks only fail below zero.

Mistakes to avoid

  • Spending bricks first and ladders after, which fails on skylines like B above.
  • Using a max-heap and popping the largest climb onto bricks, the exact opposite of what you want.
  • Pushing descents or flat steps onto the heap, which wastes ladders on free moves.
  • Returning i + 1 instead of i when bricks go negative. You are still standing on i.
  • Checking bricks before popping, so a climb that could be swapped onto a ladder is treated as a failure.

Follow-ups

  • Return which climbs used ladders. Push (rise, index) pairs; whatever is left in the heap at the end is the ladder set.
  • Ladders of different lengths. Now a ladder only covers climbs up to its length, and the problem turns into a matching question; sorting both sides and pairing greedily is a reasonable start to discuss.
  • Several kinds of resource with different costs. The heap trick relies on a ladder being worth the same on any climb. Once that breaks, expect a more general optimization.
  • Can you get to the end, yes or no? Same loop, return whether it finished.

How to explain it out loud

Fictional example

Deciding in hindsight with a heap
Candidate
Ladders should go on the biggest climbs, but I only see climbs one at a time. So I will assign each climb a ladder for now and take it back if I find a bigger climb later.
Candidate
The climbs holding ladders go in a min-heap. When there are more climbs than ladders, the smallest one switches to bricks.
Interviewer
How do you know when to stop?
Candidate
When bricks go negative. At that point the ladders are already on the largest climbs, which is the cheapest possible plan, so no other plan gets past this building either.
Candidate
Each climb is pushed and popped at most once and the heap never holds more than L plus one items, so it is O(n log L).

Minimum Cost to Hire K Workers also keeps a heap of the best few items seen so far and evicts the worst. IPO is a greedy choice backed by a heap where the proof rests on a quantity that only grows. Single-Threaded CPU uses a min-heap to decide what happens next in time order. Climbing Stairs is a far simpler walk along a row, useful as a contrast between dynamic programming and greedy.

Practicing it with Natively

The hard part here is the one-sentence justification for stopping at the first failure. When you drill this on Mac or Windows, Natively can read the skyline problem from a screenshot and describe the heap idea and the binary-search alternative, and the transcript of your practice run shows whether your explanation held together. See the AI coding interview helper for how that works.

Questions people ask

How do you solve Furthest Building You Can Reach?

Walk the buildings left to right and push every climb onto a min-heap. When the heap holds more climbs than you have ladders, pop the smallest and pay for it with bricks. When bricks drop below zero, return the current index.

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

Ladders are best spent on the largest climbs. The min-heap holds the climbs currently on ladders, so the smallest of them, the cheapest to pay in bricks, is always on top when you run short of ladders.

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

O(n log L) time and O(L) extra memory, where L is the number of ladders. A binary search on the answer with a sorting check runs in about O(n log² n).

Why does using bricks first fail?

Spending bricks on an early big climb can leave you with only ladders for small climbs and nothing for a later one. The right assignment puts ladders on the biggest climbs, which you only know in hindsight, and the heap lets you change your mind.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP