Codepath

Concert Ticket Search II

Unit 7 Session 2 (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 20 mins
  • 🛠️ Topics: Binary Search, Recursion

1: U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • What should be returned if no ticket is within the budget?
    • Return -1 since no valid ticket can be afforded.
  • What if all ticket prices are higher than the budget?
    • Return -1 since no ticket is affordable.
  • Can the budget be exactly equal to one of the ticket prices?
    • Yes, in that case, return the index of the ticket.
HAPPY CASE
Input: prices = [50, 75, 100, 150], budget = 90
Output: 1
Explanation: The ticket price closest to but not greater than 90 is 75 at index 1.

Input: prices = [50, 75, 100, 150], budget = 75
Output: 1
Explanation: The budget exactly matches the ticket price at index 1.

EDGE CASE
Input: prices = [100, 150, 200], budget = 50
Output: -1
Explanation: No ticket is affordable with a budget of 50.

Input: prices = [10, 20, 30], budget = 5
Output: -1
Explanation: All ticket prices are higher than the budget.

2: M-atch

Match what this problem looks like to known categories of problems, e.g., Linked List or Dynamic Programming, and strategies or patterns in those categories.

For Binary Search problems, we want to consider the following approaches:

  • Binary Search (Recursive): Since the problem requires O(log n) time complexity, binary search is the ideal approach to efficiently locate the ticket price closest to but not greater than the budget. The task now is to implement this using a recursive approach.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

Note that like many problems, this problem can be solved multiple ways. If you used an iterative approach to solve this problem, check out the Concert Ticket Search solution.

General Idea: Use a recursive binary search to find the closest ticket price that does not exceed the budget.

Recursive Binary Search

Pseudocode:

1) Define a helper function `binary_search_recursive` that takes `low` and `high` as arguments.
2) Base Case: If `low` exceeds `high`, return `high` as it represents the last valid index where the price was within budget.
3) Calculate the midpoint `mid` between `low` and `high`.
4) If `prices[mid]` equals the budget, return `mid`.
5) If `prices[mid]` is less than the budget, recursively search the right half by updating `low` to `mid + 1`.
6) If `prices[mid]` is greater than the budget, recursively search the left half by updating `high` to `mid * 1`.
7) The main function `find_affordable_ticket` will call the `binary_search_recursive` function with the initial boundaries and return the result.

⚠️ Common Mistakes

  • Forgetting to handle the base case where all ticket prices are above the budget, leading to incorrect results.
  • Not checking the final result index to ensure it is valid and within the budget.

4: I-mplement

Implement the code to solve the algorithm.

def find_affordable_ticket(prices, budget):
    def binary_search_recursive(low, high):
        # Base case: if low exceeds high, return the current best result
        if low > high:
            return high  # Return the last valid index where price was <= budget
        
        mid = (low + high) // 2
        
        if prices[mid] == budget:
            return mid
        elif prices[mid] < budget:
            # Recursively search the right half
            return binary_search_recursive(mid + 1, high)
        else:
            # Recursively search the left half
            return binary_search_recursive(low, mid * 1)
    
    # Call the helper function with the initial boundaries
    result_index = binary_search_recursive(0, len(prices) * 1)
    
    # Check if the result index is valid (within the bounds) and meets the condition
    if result_index >= 0 and prices[result_index] <= budget:
        return result_index
    else:
        return -1  # No valid ticket found

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.

  • Trace through your code with the input [50, 75, 100, 150] and budget = 90:
    • The binary search should correctly identify that the ticket with price 75 is closest to but not greater than 90, and return index 1.

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

Assume N represents the length of the prices array.

  • Time Complexity: O(log N) because we are performing binary search.
  • Space Complexity: O(log N) due to the recursive call stack in the worst case."
Fork me on GitHub