Check if it is possible to serve customer queue with different notes in Python

Suppose we have an array called notes representing different rupee notes held by customers in a queue. They are all waiting to buy tickets worth Rs 50. The possible notes are [50, 100, and 200]. We need to check whether we can sell tickets to all customers in order, starting with Rs 0 in our hand.

For example, if the input is notes = [50, 50, 100, 100], the output will be True. For the first two customers, we don't need to return any change, but we collect two Rs 50 notes. For the last two customers with Rs 100 notes, we can return Rs 50 as change and successfully serve everyone.

Algorithm Steps

To solve this problem, we follow these steps ?

  • Create a frequency map to track available notes
  • For each customer in the queue:
    • If they pay Rs 50: Add it to our collection
    • If they pay Rs 100: We need Rs 50 change, check availability
    • If they pay Rs 200: We need Rs 150 change (prefer one Rs 100 + one Rs 50, or three Rs 50)
  • Return True if we can serve all customers, False otherwise

Example Implementation

Let us see the following implementation to get better understanding ?

from collections import defaultdict

def solve(notes):
    freq = defaultdict(int)
    i = 0
    
    while i < len(notes):
        if notes[i] == 50:
            freq[50] += 1
        elif notes[i] == 100:
            freq[100] += 1
            if freq[50] == 0:
                break
            freq[50] -= 1
        else:  # notes[i] == 200
            if freq[100] > 0 and freq[50] > 0:
                freq[100] -= 1
                freq[50] -= 1
            elif freq[50] >= 3:
                freq[50] -= 3
            else:
                break
        i += 1
    
    if i == len(notes):
        return True
    return False

# Test the function
notes = [50, 50, 100, 100]
print(solve(notes))
True

How It Works

The algorithm simulates the ticket selling process:

  • Rs 50 payment: No change needed, we keep the note
  • Rs 100 payment: Need Rs 50 change, check if we have it available
  • Rs 200 payment: Need Rs 150 change, prefer giving one Rs 100 + one Rs 50 (optimal) or three Rs 50 notes

Additional Test Cases

# Test case 1: Cannot serve all customers
notes1 = [100, 50, 50]
print(f"Test 1: {solve(notes1)}")

# Test case 2: Can serve with Rs 200 notes
notes2 = [50, 50, 50, 100, 200]
print(f"Test 2: {solve(notes2)}")

# Test case 3: Cannot serve Rs 200 customer
notes3 = [50, 200]
print(f"Test 3: {solve(notes3)}")
Test 1: False
Test 2: True
Test 3: False

Conclusion

This greedy approach efficiently determines if we can serve all customers by tracking available notes and making optimal change decisions. The key insight is prioritizing Rs 100 notes for Rs 200 customers to preserve Rs 50 notes for future Rs 100 customers.

Updated on: 2026-03-25T15:13:10+05:30

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements