</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Greedy with Heap

What is this?

A greedy algorithm makes the best choice available right now and trusts that this adds up to the best overall answer. The catch is that "best available" keeps changing as new options open up and old ones expire. A heap keeps that moving target in order so the current best is always one quick pop away.

flowchart TD A["New Options Unlock"] --> B["Push onto Heap"] B --> C["Pop the Best Now"] C --> D["Take Greedy Step"] D --> A

๐Ÿ’ก Fun fact: This "always grab the best option now" idea is the same engine behind Dijkstra's famous shortest-path algorithm, which finds the fastest route through a map by repeatedly popping the closest unvisited place from a heap.

๐Ÿ”“ The 2 problems in this chapter are free. Sign in with Google or Microsoft to start solving.


Core idea: Many greedy algorithms repeat the same move: at each step, take the best available option right now. The trouble is that "best available" changes as you go โ€” new options unlock, old ones expire. A heap maintains that shifting frontier so the current extreme is always one pop away. A close cousin, the monotonic stack, applies the same greedy instinct to ordering: keep the stack as good as possible and pop whatever blocks a better arrangement.


The pattern

Greedy works when a locally optimal choice is provably part of a globally optimal answer. The data structure's job is to surface that locally optimal choice cheaply.

  • A heap lets you re-evaluate "what's best now" after each step in O(log n), which is exactly what you need when the set of affordable or reachable options grows over time.
  • A monotonic stack enforces a greedy ordering: you push candidates and pop any that a later, better candidate makes obsolete โ€” as long as a guard tells you the popped element will appear again.

The problems

  • IPO โ€” you can fund projects whose capital requirement you can currently afford. As your capital grows, more projects unlock. Push every affordable project's profit into a max-heap, pop the most profitable, add its profit to your capital, and repeat. The heap tracks the moving affordability threshold.
  • Remove Duplicate Letters โ€” build the lexicographically smallest result with each letter once. Use a monotonic stack: before pushing a letter, pop larger letters off the top only if they still occur later (a last-occurrence guard). The guard is what makes the greedy pop safe.

Key takeaways

  • Greedy = best choice now โ€” correct only when local optimality implies global optimality.
  • Heap surfaces the current extreme as the option set shifts (IPO's unlocking projects).
  • Push what becomes available, pop what's best โ€” the two-heap-free engine behind IPO.
  • Monotonic stack greedily fixes ordering โ€” pop worse elements, guarded by last-occurrence so you never lose a required letter.
  • Why interviewers love it: it tests whether you can prove the greedy move is safe, not just code it.

Order: IPO โ†’ Remove Duplicate Letters.

IPO

Core idea: Your spending power grows as you finish projects, so the set of things you can afford keeps expanding. At every step, unlock everything you can now afford and greedily grab the single most profitable one โ€” a min-heap (or sorted pointer) feeds affordability into a max-heap of profits.


Problem, rephrased

Forget the textbook phrasing. Here's the scenario:

You're a startup with w dollars of working capital. There are several projects you could take on. Each project has two numbers: a capital requirement (cash you must already have on hand to start it) and a profit (pure profit it pays out when finished โ€” your capital goes up by that amount, and the requirement is never spent, just gated on).

You can complete at most k projects, one after another. After each finished project, your capital is larger, so projects that were once out of reach may now be affordable. Choose wisely to maximize your final capital.

This is LeetCode 502, "IPO" โ€” you're trying to grow rich enough to go public.

w (start) k profits capital Final capital Why
0 2 [1, 2, 3] [0, 1, 1] 4 afford only P0 โ†’ +1 (cap 1); now afford P2 โ†’ +3 (cap 4)
0 1 [1, 2, 3] [0, 1, 1] 1 one pick, only P0 is affordable at start โ†’ +1
2 3 [5, 4, 8] [0, 2, 4] 19 grab biggest affordable each round: +8, +5, +4

The output is a single number โ€” the final capital โ€” not the list of projects chosen.


Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.