Taro Logo

Lemonade Change

#103 Most AskedEasy
Topics:
ArraysGreedy Algorithms

At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.

Note that you do not have any change in hand at first.

Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.

Example 1:

Input: bills = [5,5,5,10,20]
Output: true
Explanation: 
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.

Example 2:

Input: bills = [5,5,10,10,20]
Output: false
Explanation: 
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can not give the change of $15 back because we only have two $10 bills.
Since not every customer received the correct change, the answer is false.

Constraints:

  • 1 <= bills.length <= 105
  • bills[i] is either 5, 10, or 20.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are there any bills other than 5, 10, or 22 dollars that could appear in the input array?
  2. What should happen if the input array of bills is empty or null?
  3. Can we assume the customers always line up in the exact order given by the array, and we must serve them sequentially?
  4. If a customer pays with a 22-dollar bill, what specific combination of change should we attempt to give back first?
  5. Are we guaranteed that the input array only contains positive integers representing valid bill denominations?

Brute Force Solution

Approach

Imagine you are running a lemonade stand where every drink costs the same amount, and you need to figure out how to give correct change to every customer in line. The brute force approach involves looking ahead at all possible combinations of change-giving strategies to see if you can successfully get through the entire line of customers without ever running out of the right bills.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the first customer in line and note the bill they hand you.
  2. If they pay with the exact amount, happily take the money and do nothing extra, then move to the next person.
  3. If they pay with a larger bill, imagine every possible combination of smaller bills you currently possess that could add up to the exact required change.
  4. Try giving one of those combinations to the customer.
  5. Then, look ahead to the next customer in line and repeat the process of trying every possible change combination for them too.
  6. If you ever reach a point where you cannot make correct change using any combination of bills you have, pretend you made a wrong choice earlier and go back to try a different combination.
  7. Continue exploring every possible path of giving change until you either successfully serve every single customer or prove that no combination works.

Code Implementation

class LemonadeStandSolver:
    def lemonadeChange(self, customer_bills: list[int]) -> bool:
        
        def explore_change_combinations(customer_index: int, five_dollar_bills: int, ten_dollar_bills: int) -> bool:
            if customer_index == len(customer_bills):
                return True
            
            current_payment = customer_bills[customer_index]
            
            # We branch through all possible bill combinations to ensure every future path is fully explored
            if current_payment == 5:
                return explore_change_combinations(customer_index + 1, five_dollar_bills + 1, ten_dollar_bills)
            
            elif current_payment == 10:
                if five_dollar_bills >= 1:
                    if explore_change_combinations(customer_index + 1, five_dollar_bills - 1, ten_dollar_bills + 1):
                        return True
                return False
            
            elif current_payment == 20:
                # Backtracking requires checking a 10 and a 5 first before trying three 5 bills for change
                if ten_dollar_bills >= 1 and five_dollar_bills >= 1:
                    if explore_change_combinations(customer_index + 1, five_dollar_bills - 1, ten_dollar_bills - 1):
                        return True
                
                if five_dollar_bills >= 3:
                    if explore_change_combinations(customer_index + 1, five_dollar_bills - 3, ten_dollar_bills):
                        return True
                        
                return False
            
            return False

        return explore_change_combinations(0, 0, 0)

Big(O) Analysis

Time Complexity
O(2^n) – For each of the n customers in line, the brute force approach recursively explores multiple branching choices of change combinations to see if future customers can be served. At each step, the algorithm may branch into multiple paths as it tries different valid bills from our register. In the worst-case scenario, this exploration resembles a binary or ternary tree of depth n, leading to approximately 2^n or 3^n total operations. Simplifying this exponential growth results in a final Big O time complexity of O(2^n).
Space Complexity
O(1) – To determine if we can serve all N customers, we only need to track the count of five-dollar and ten-dollar bills currently in our register using a few integer variables. The brute-force exploration described, which involves backtracking and trying every combination of bills, does not require a deep recursion stack or auxiliary data structures because we can always greedily make change. Consequently, the auxiliary memory used remains constant regardless of the number of customers N, leading to an optimal O(1) space complexity.

Optimal Solution

Approach

The optimal strategy is a greedy approach that processes customers one by one while keeping a running count of the smaller bills available in the cash register. Whenever change is needed, it always prioritizes handing back the largest possible bill first, which preserves the smaller bills for future customers who might need exact change.

Here's how the algorithm would work step-by-step:

  1. Greet the first customer and look at the bill they hand you for their drink.
  2. If the customer pays with a small bill, accept it and add it to your register collection without needing to give any change.
  3. If the customer pays with a medium bill, check your register for a small bill to give back as change.
  4. If you successfully hand back the correct change, add the customer's medium bill to your register.
  5. If the customer pays with a large bill, first check if you can give back a medium bill combined with a small bill, because this is the smartest way to save your remaining small bills.
  6. If you do not have the medium and small bill combination, check if you have three small bills instead to hand back as change.
  7. Repeat this exact decision-making process for every single customer standing in line.
  8. If at any point you cannot make the required change, stop and recognize that it is impossible to serve everyone.
  9. If you successfully manage the payments for every customer in line, you have won the challenge.

Code Implementation

class Solution:
    def lemonadeChange(self, customer_bills: list[int]) -> bool:
        count_five_dollar_bills = 0
        count_ten_dollar_bills = 0
        
        for current_bill in customer_bills:
            if current_bill == 5:
                count_five_dollar_bills += 1
            elif current_bill == 10:
                # A ten-dollar payment requires returning a five-dollar bill as change.
                if count_five_dollar_bills > 0:
                    count_five_dollar_bills -= 1
                    count_ten_dollar_bills += 1
                else:
                    return False
            else:
                # Prioritize using a ten and a five to preserve smaller bills.
                if count_ten_dollar_bills > 0 and count_five_dollar_bills > 0:
                    count_ten_dollar_bills -= 1
                    count_five_dollar_bills -= 1
                elif count_five_dollar_bills >= 3:
                    count_five_dollar_bills -= 3
                else:
                    return False
                    
        return True

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of customers in the line whose bills we must process one by one in a single pass. For each customer, we perform a constant number of arithmetic operations and conditional checks on our running count of register bills without using any nested loops or inner traversals. This leads to approximately a constant number of operations per customer, or 1 times n total steps. Simplifying this linear progression yields a final runtime complexity of O(n).
Space Complexity
O(1) – The algorithm maintains a running count of the smaller bills available in the cash register using only a fixed number of scalar integer variables to track the frequencies of five-dollar and ten-dollar bills. Because these few primitive counters take up a constant amount of memory that does not scale with the number of customers, the extra space required remains entirely independent of the input size N. Therefore, the auxiliary space complexity is constant, simplifying to Big O of 1.

Edge Cases

Empty bills array
How to Handle:
Return true immediately since no transactions need to be processed.
Single customer paying with a 5 dollar bill
How to Handle:
No change is needed, so we increment our 5 dollar count and return true.
Single customer paying with a 10 or 22 dollar bill
How to Handle:
Return false instantly because we do not have any 5 dollar bills in hand to provide change.
Customer pays with 22 dollars when we only have 5 dollar bills
How to Handle:
Greedily use one 10 dollar bill and two 5 dollar bills if available, or three 5 dollar bills otherwise.
Customer pays with 10 dollars when we have zero 5 dollar bills
How to Handle:
Return false because we cannot make change for the 10 dollar bill without a 5 dollar bill.
Customer pays with 22 dollars and we have both 10 and 5 dollar bills available
How to Handle:
Greedily give one 10 and one 5 dollar bill rather than three 5s to preserve smaller bills for future 10 dollar changes.
Extremely large queue of customers up to the maximum constraints
How to Handle:
Process the array in a single linear scan with O(1) space complexity to ensure optimal performance without memory limits.
Invalid bill denominations not equal to 5, 10, or 22
How to Handle:
Treat unrecognized bills as incapable of being accepted and immediately return false.
0/245 completed