githubEdit

13. Bus Ticket Change

βœ… GFG solution to the Bus Ticket Change problem using a greedy strategy to ensure correct change for every customer in sequence. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

You are given an array arr[] representing passengers in a queue. Each bus ticket costs 5 coins, and arr[i] denotes the note a passenger uses to pay (which can be 5, 10, or 20). You must serve the passengers in the given order and always provide the correct change so that each passenger effectively pays exactly 5 coins. Your task is to determine whether it is possible to serve all passengers in the queue without ever running out of change.

πŸ“˜ Examples

Example 1

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

Example 2

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

πŸ”’ Constraints

  • $1 \le \text{arr.size()} \le 10^5$

  • $\text{arr}[i]$ contains only [5, 10, 20]

βœ… My Approach

The optimal approach uses a Greedy Strategy with denomination tracking to efficiently validate change-making capability:

Greedy Change Management

  1. Initialize Counters:

    • Track two counters: f (count of 5-coin notes) and t (count of 10-coin notes).

    • These represent the available change at any point.

  2. Process Each Payment:

    • For 5-coin payment: Simply increment the count of 5-coin notes (no change needed).

    • For 10-coin payment: Check if we have at least one 5-coin note for change. If yes, give it and store the 10-coin note. Otherwise, return false.

    • For 20-coin payment: Apply greedy strategy - prefer giving one 10-coin and one 5-coin note (to preserve 5-coin notes). If not possible, give three 5-coin notes. If neither option works, return false.

  3. Greedy Optimization:

    • Always prefer larger denominations when giving change for 20-coin payments.

    • This preserves smaller 5-coin notes which are more versatile for future transactions.

  4. Validation:

    • If all passengers are served successfully without running out of change, return true.

    • Return false immediately upon first failure to provide correct change.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), where n is the size of the array. We process each passenger exactly once in a single pass through the array.

  • Expected Auxiliary Space Complexity: O(1), as we only use two integer variables to track the count of 5-coin and 10-coin notes, regardless of input size.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Single Pass with Early Exit

πŸ’‘ Algorithm Steps:

  1. Track counts of 5 and 10 rupee notes in hand.

  2. Process each customer payment sequentially.

  3. Return immediately if unable to provide change.

  4. Optimize change-giving strategy to preserve smaller denominations.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Single pass through array

  • Auxiliary Space: πŸ’Ύ O(1) - Only two counters used

βœ… Why This Approach?

  • Clean conditional structure for each case

  • Early exit on first failure improves average performance

  • Explicit handling of all payment scenarios

πŸ“Š 3️⃣ Switch-Case Pattern

πŸ’‘ Algorithm Steps:

  1. Use switch statement for clear case handling of different bills.

  2. Maintain denomination counters for available change.

  3. Apply greedy strategy preferring larger notes first.

  4. Validate change availability before accepting payment.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Linear iteration through payments

  • Auxiliary Space: πŸ’Ύ O(1) - Fixed array of size 2

βœ… Why This Approach?

  • Switch statement provides clear branching logic

  • Array storage for scalable denomination tracking

  • Structured approach suitable for code maintenance

πŸ“Š 4️⃣ Bitwise State Compression

πŸ’‘ Algorithm Steps:

  1. Pack both counters into single integer using bit manipulation.

  2. Extract and update counts using bitwise operations.

  3. Process payments with compact state representation.

  4. Reduce memory footprint while maintaining logic.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Same linear scan with bitwise ops

  • Auxiliary Space: πŸ’Ύ O(1) - Single integer for state

βœ… Why This Approach?

  • Minimized variable usage through bit packing

  • Educational demonstration of state compression

  • Maintains constant space with clever encoding

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ Greedy Counter

🟒 O(n)

🟒 O(1)

πŸš€ Optimal and simple

πŸ”§ Requires careful logic

πŸ” Early Exit

🟒 O(n)

🟒 O(1)

⚑ Fast on invalid inputs

πŸ“ More verbose conditionals

πŸ“Š Switch-Case

🟒 O(n)

🟒 O(1)

πŸ“– Clear case separation

πŸ”§ Slightly more code

πŸ”„ Bitwise Compression

🟒 O(n)

🟒 O(1)

πŸ’Ύ Ultra-compact state

🧠 Less readable code

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Production code

πŸ₯‡ Greedy Counter

β˜…β˜…β˜…β˜…β˜…

πŸ“– Interview clarity

πŸ₯ˆ Early Exit

β˜…β˜…β˜…β˜…β˜…

πŸ”§ Structured design

πŸ₯‰ Switch-Case

β˜…β˜…β˜…β˜…β˜†

🎯 Memory-constrained

πŸ… Bitwise Compression

β˜…β˜…β˜…β˜†β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated