Lemonade Change
What is this problem about?
The "Lemonade Change interview question" is a delightful problem about managing currency. You are running a lemonade stand where each drink costs 5.Customersstandinaqueueandpaywitheithera5, 10,or20 bill. You must provide the correct change to each customer. Initially, you have no money. The goal is to determine if you can provide change to every customer in the order they arrive. This "Lemonade Change coding problem" is a classic example of greedy decision-making.
Why is this asked in interviews?
This problem is a staple in entry-level interviews because it tests "Greedy interview pattern" logic and state management. It's simple on the surface but requires you to make the right choice when giving change for a 20bill.Itevaluateswhetheryoucanidentifythata10 bill is "less flexible" than two $5 bills and should therefore be used as change first.
Algorithmic pattern used
The Greedy approach is the key. You maintain a count of the 5and10 bills you have. When a customer pays:
- **5bill:∗∗Nochangeneeded.Increment5 count.
- **10bill:∗∗Need5 change. If you have one, decrement 5countandincrement10 count. Otherwise, return false.
- **20bill:∗∗Need15 change. You have two options: one 10+one5, or three 5s.Thegreedychoiceistousethe10 bill first because $5 bills are more versatile for future customers.
Example explanation
Queue: [5, 5, 10, 10, 20]
- **5:∗∗Haveone5.
- **5:∗∗Havetwo5s.
- **10:∗∗Giveone5 as change. Now have one 5,one10.
- **10:∗∗Giveone5 as change. Now have zero 5s,two10s.
- **20:∗∗Need15 change. We have two 10sbutno5s. We cannot give change. Result: False.
Common mistakes candidates make
- Poor Greedy Choice: Using three 5billstochangea20 when a 10anda5 were available.
- **Tracking 20bills:∗∗Thinkingyoucanuse20 bills to give change (you can't, since the maximum change needed is $15).
- Queue order: Forgetting that you must serve customers in the exact order they appear in the array.
Interview preparation tip
In greedy problems, always ask: "Is there an item that is more valuable to keep for later?" In this case, 5billsarethemostvaluablebecausetheycanchangeboth10 and 20bills,whereas10 bills can only help with $20 bills.