Lemonade Change solution explained

Lemonade Change is solved by counting the five and ten bills in the till and, when a customer pays with a twenty, handing back a ten plus a five before falling back to three fives. That single greedy rule answers whether every customer in the line can get correct change, in O(n) time and O(1) extra space.

By Published 8 min read

What the problem asks

Picture a street stall that charges five for a cup. People queue up and each one buys exactly one cup, paying with a single bill worth five, ten or twenty. The till is empty when the stall opens. As each person pays, you must hand back their change right away using only bills already in the till. Given the sequence of bills in queue order, return true if you can serve the whole line, and false the moment one person cannot get correct change.

Queues invented for this walkthrough
Bills in orderResultWhat happens
[5, 5, 10, 20]trueTwo fives in; the ten takes one five back; the twenty gets the ten and the last five.
[5, 10, 10]falseThe second ten needs a five, but the only five already went out.
[10, 5]falseThe very first customer needs change from an empty till.
[5, 5, 5, 5, 10, 20, 10]trueOnly works if the twenty receives the ten plus a five, leaving a five for the last customer.
[5, 5, 5, 20, 10]falseWith no ten in the till, the twenty takes all three fives and the next ten is stuck.
Queues invented for this walkthrough. Scroll sideways on a small screen.

Two quick questions are worth asking before you code. Can the input contain any bill other than five, ten and twenty? Does the stall ever get to take bills out of order, for example by serving a later customer first? The usual answer is no to both, which is what keeps the problem small.

Why it shows up in screens

This is a short problem with a real lesson. It checks whether you can model state with the fewest variables, and, more importantly, whether you can justify a greedy choice instead of guessing it. Interviewers often use it as a warm-up before a harder problem, or as a gentle way to ask the question every greedy solution invites: why is the local choice safe?

A slow but sure approach: try every way to make change

Fives need no change. A ten always needs exactly one five back, so there is no choice there. A twenty is the only bill with two possible answers: a ten and a five, or three fives. If you are not sure which to pick, try both. A recursive search walks the queue, carrying the counts of fives and tens, and branches at every twenty where both options are affordable.

def serve_all_search(bills, i=0, fives=0, tens=0):
    if i == len(bills):
        return True
    bill = bills[i]
    if bill == 5:
        return serve_all_search(bills, i + 1, fives + 1, tens)
    if bill == 10:
        return fives > 0 and serve_all_search(bills, i + 1, fives - 1, tens + 1)
    if tens > 0 and fives > 0 and serve_all_search(bills, i + 1, fives - 1, tens - 1):
        return True
    return fives >= 3 and serve_all_search(bills, i + 1, fives - 3, tens)
Backtracking: correct, but up to two branches per twenty, so O(2^t) for t twenties.

Mentioning this version is useful even if you never run it. It makes the only real decision in the problem visible, and the next step is to prove that one branch is always at least as good as the other.

The greedy approach and why it is safe

Keep two counters, fives and tens. You do not need to count twenties because no customer can ever receive one. For each bill:

  1. A five: add one to fives.
  2. A ten: if fives is zero, return false. Otherwise take one five away and add one ten.
  3. A twenty: if you hold at least one ten and one five, give those. Else if you hold three fives, give those. Else return false.

The argument for the third rule is short. A five can pay change for a ten or for a twenty, while a ten is only good for a twenty. Both ways of breaking a twenty hand back the same amount, but the ten-and-five option spends one five and the other spends three. Suppose some successful plan breaks a twenty with three fives while a ten was in the till. Swap it: give the ten and one five instead. You now hold two extra fives and one fewer ten. Every later step that the old plan paid with that ten can be paid with two of those fives, and every other step is unchanged, so the new plan still succeeds. Repeat the swap and you reach the greedy plan without ever breaking anything.

def serve_all(bills):
    fives = tens = 0
    for bill in bills:
        if bill == 5:
            fives += 1
        elif bill == 10:
            if fives == 0:
                return False
            fives -= 1
            tens += 1
        elif tens > 0 and fives > 0:
            tens -= 1
            fives -= 1
        elif fives >= 3:
            fives -= 3
        else:
            return False
    return True
Python: one pass with two counters.
function serveAll(bills) {
  let fives = 0;
  let tens = 0;
  for (const bill of bills) {
    if (bill === 5) {
      fives++;
    } else if (bill === 10) {
      if (fives === 0) return false;
      fives--;
      tens++;
    } else if (tens > 0 && fives > 0) {
      tens--;
      fives--;
    } else if (fives >= 3) {
      fives -= 3;
    } else {
      return false;
    }
  }
  return true;
}
JavaScript: the same counters, returning on the first failure.

Trace [5, 5, 5, 5, 10, 20, 10]. After four fives the till holds four fives. The ten makes it three fives and one ten. The twenty takes the ten and a five, leaving two fives. The last ten takes one five and the answer is true. Had the twenty taken three fives, the till would hold one ten and no fives, and the final customer would be stuck.

Cost of each version

Running time and memory, n customers and t twenties
VersionTimeExtra memoryComment
Backtracking over both change optionsO(2^t) worst caseO(n) recursion depthOnly useful to show the decision point
Greedy with two countersO(n)O(1)The expected answer
Running time and memory, n customers and t twenties. Scroll sideways on a small screen.

Edge cases worth saying out loud

  • An empty queue: nobody needs change, so the answer is true.
  • A first customer paying with a ten or a twenty: false immediately, since the till starts empty.
  • A queue of only fives: always true, and the till just grows.
  • Many twenties in a row after a few fives: each needs three fives once the tens run out, so the fives drain fast.
  • A long queue in Python: the greedy loop has no recursion, so there is no depth limit to worry about. The search version would hit Python's recursion limit on long inputs, which is one more reason not to ship it.

Mistakes that show up in mock rounds

  • Checking three fives before ten-plus-five for a twenty. It passes many tests and fails exactly the case in the fourth row of the table above.
  • Tracking the total cash in the till instead of the bills. Thirty in the till as one twenty and one ten cannot change a ten, so the sum is the wrong state.
  • Forgetting to add the ten to the till after giving change for it, which makes later twenties fail for no reason.
  • Adding a twenties counter and then using it as change. Bills larger than the change owed are useless here.
  • Claiming the greedy rule is right without a reason. Interviewers usually ask for the exchange argument, so have the two-sentence version ready.

Follow-up questions

  • What if the bill values were arbitrary? Greedy change-making is not correct for every coin system. With general denominations you would track counts of each bill and search, or use dynamic programming over amounts, and the problem gets much harder.
  • Return the position of the first customer who cannot be served. Same loop; return the index instead of false.
  • Customers may buy several cups. The change owed becomes a variable amount, and you need a rule for which bills to hand back first. Largest-first works for fives, tens and twenties, but say why.
  • You may start with some change in the till. Initialize the two counters with those values; nothing else moves.

Saying it in an interview

Fictional example

A short explanation a candidate might give
Candidate
The state is just how many fives and tens I hold. Twenties never come back out, so I do not count them.
Candidate
The only choice is how to break a twenty. I give a ten and a five when I can, because a five can also serve a later ten and a ten cannot, so keeping fives never hurts.
Candidate
It is one pass, constant memory. If a ten arrives with no five, or a twenty with neither option available, I return false right there.

Where to go next in this batch

Queue Reconstruction by Height is another greedy problem where the order in which you decide things carries the whole proof, and Sort Characters by Frequency practices the counting habit from a different angle. For the wider set of patterns, see the algorithm interview questions guide.

Rehearsing it with Natively

When you practice at your desk, Natively can read a screenshot of a problem like this, suggest a pattern and draft code, which is handy for checking your own greedy argument after you have written it. It also transcribes a mock round on your computer, so afterwards you can see whether you explained why ten-and-five comes first or skipped straight to code. More on an AI interview assistant for Mac and Windows.

Questions people ask

What is the optimal solution to Lemonade Change?

Walk the queue once with two counters, one for fives and one for tens. A ten takes one five back; a twenty takes a ten and a five if possible, otherwise three fives. It runs in O(n) time and O(1) space.

Why give a ten and a five before three fives?

Both hand back the same amount, but fives can pay change for tens and twenties while tens only help with twenties. Spending one five instead of three leaves the till strictly more flexible.

Do you need to count twenty-dollar bills?

No. Change is never more than fifteen, so a twenty can never be handed back. Counting them adds state without changing any answer.

Is Lemonade Change a greedy problem?

Yes. It is a small, clean example of a greedy choice backed by an exchange argument, which is why interviewers like to ask for the reasoning, not just the code.

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