You sell lemonade for $5 a cup. Customers come one at a time in the order given by bills, and each buys one cup, paying with a $5, $10 or $20 bill.
You start with no money at all. Each customer must get back exactly the difference, using only bills you have collected so far. Return true if you can give every customer the right change, and false otherwise.
Example 1
Input: bills = [5, 10, 5, 20, 5, 10] Output: true Why: the 20 gets a 10 and a 5 back; every other change is a 5
2 more examples and the constraints
Example 2
Input: bills = [5, 5, 10, 20, 20] Output: false Why: the first 20 empties the drawer, so the second gets nothing
Example 3
Input: bills = [10, 5] Output: false Why: the first customer needs a 5 and we have none
Constraints
- 1 ≤ length of bills ≤ 100,000
- Every bills[i] is 5, 10 or 20
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Keep every bill in a listO(n²)
- Count fives and tensO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 customers | Verdict |
|---|---|---|---|
| Keep every bill in a list | O(n²) | Correct, but slow on big inputs | |
| Count fives and tens | O(n) | Best; two counters |
n = the number of customers.
Edge cases to test
- First bill is not a 5. [10, 5] or [20] fails at once: the drawer starts empty.
- A 20 with only 5s. [5, 5, 5, 20] works with three 5s.
- Choosing the wrong change. [5, 5, 5, 5, 10, 20, 10, 10] works only if the 20 gets 10 + 5; paying it with three 5s leaves no 5 for the last 10.
- Only fives. Always true: nobody needs change.
Common mistakes
- Giving three 5s for a 20 even when a 10 is available, which can strand a later $10 customer.
- Forgetting to add the customer's 10 to the drawer after giving change.
- Checking
five >= 1for a 20 without also checking that a 10 is there.
How to talk through it
- 1Clarify. Do I start with no money? Are the only bills 5, 10 and 20? Must the order of customers be kept?
- 2Simulate first. Keep the drawer as a list and act out each sale; slow because of list searches.
- 3Shrink the state. Bills of the same value are interchangeable, and a 20 is never change, so two counters are enough.
- 4Explain the greedy. For a 20, give 10 + 5 before 5 + 5 + 5, because fives are useful to every customer and tens only to a 20.
- 5Test out loud. Run a first bill of 10, a 20 paid with three 5s and the case where the wrong choice fails.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?