</> 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 Choice

What is this?

A greedy choice means picking what looks best right this second and never taking it back, the way you hand over the biggest coins first when making change. The catch is that grabbing the best-looking option does not always lead to the best overall result, so the real work here is convincing yourself that the local pick is safe. Once you trust the order to pick things in, the actual solving is a quick single pass.

flowchart TD A["Define the best next move"] --> B["Sort by that key"] B --> C["Take greedily from the top"] A --> D["Or test a few candidate answers"] C --> E["Argue no swap can do better"]

๐Ÿ’ก Fun fact: Sometimes only a handful of values can possibly be the answer, so trying every candidate is still fast. For the domino puzzle here, the winning value must appear on the very first domino, which leaves just two options to check out of all the possibilities.

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


Core idea: a greedy algorithm builds an answer by repeatedly taking the choice that looks best right now and never reconsidering it. The whole challenge is justifying that the local best is also globally safe โ€” once you trust the ordering, the solution is a short, fast scan.

The pattern

Each problem here picks a clear notion of "best next move" and commits to it. The supporting argument is an exchange or case analysis showing the greedy choice loses nothing.

  • Sort by value density, then take. When you have a capacity to fill with items of differing worth, rank items by worth per unit and take from the top until full. Any swap toward a lower-density item can only reduce the total, so the greedy order is optimal.
  • Try the few candidate targets. When the goal is to make everything equal and only a handful of values could possibly work, enumerate those candidates explicitly, test each for feasibility, and take the cheapest. The candidate set is tiny, so trying all of them is cheap and exhaustive.

The common thread: define the local criterion, argue it is safe, and let a single pass (after an optional sort) finish the job.

The problems

Maximum Units on a Truck โ€” each box type carries a number of units; the truck holds a fixed number of boxes. Sort box types by units per box descending, then load greedily from the densest type until the truck is full. Trading any loaded box for a lower-unit one only loses units, so the sort order is optimal.

Minimum Domino Rotations for Equal Row โ€” to make one row of a domino pair all identical, the common value must be either the top or the bottom of the first domino โ€” only two candidates. For each candidate, check that every domino can show it on the chosen row, count the rotations needed for top and bottom, and keep the minimum; if neither candidate is feasible, it is impossible.

Key takeaways

  1. Greedy builds an answer one locally optimal choice at a time and never backtracks.
  2. The real work is the justification โ€” an exchange argument or case check that the local best is globally safe.
  3. Sorting by value density and taking from the top maximizes worth under a capacity limit.
  4. When only a few values could be the answer, enumerate and test those candidates directly.
  5. Once the ordering is trusted, greedy solutions are short, fast, and usually one pass after a sort.

Minimum Domino Rotations For Equal Row

Core idea: You have a row of dominoes split into a tops[] half and a bottoms[] half; rotating domino i swaps tops[i] with bottoms[i]. You want one entire half โ€” all of tops or all of bottoms โ€” to show a single repeated value, using the fewest rotations. The trap is imagining you must search every value 1..6. You don't. Whatever the winning value v is, it has to work for domino 0 too, so v is forced to be either tops[0] or bottoms[0] โ€” at most two candidates. For each candidate, sweep the row once: if some domino contains v on neither face, that candidate is impossible; otherwise count how many tops lack v (rotations to fill the top) and how many bottoms lack v (rotations to fill the bottom), and take the smaller. The overall answer is the best over the โ‰ค2 candidates, or -1 if both fail. O(n) time, O(1) space.


The problem, rephrased

You're laying out a line of dominoes on a table. Each domino has been printed with a number on its top half and a number on its bottom half (every number is 1โ€“6). You're allowed to grab any domino and flip it end-over-end, which swaps its top and bottom numbers. Your goal: get an entire row showing the same number โ€” either every top reads the same, or every bottom reads the same. Each flip costs one move. Return the minimum number of flips, or -1 if no amount of flipping can make a uniform row.

This is LeetCode 1007 โ€” Minimum Domino Rotations For Equal Row.

Input Means Output
tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2] 6 dominoes, two faces each 2
tops = [3,5,1,2,3], bottoms = [3,6,3,3,4] 5 dominoes -1
tops = [1,2,1,1,1,2,2,2], bottoms = [2,1,2,2,2,2,2,2] 8 dominoes 1

You return a single integer: the fewest rotations, or -1 when it's impossible.


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.