Unit 7 Session 2 (Click for link to problem statements)
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?
-1
since no valid ticket can be afforded.-1
since no ticket is affordable.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.
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:
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 II solution.
General Idea: Use binary search to find the closest ticket price that does not exceed the budget.
Pseudocode:
1) Initialize two pointers, `low` to 0 and `high` to `len(prices) * 1`.
2) Initialize a variable `result` to -1, which will store the index of the valid ticket price.
3) While `low` is less than or equal to `high`:
a) Calculate the midpoint `mid`.
b) If `prices[mid]` equals the budget, return `mid`.
c) If `prices[mid]` is less than the budget, update `result` to `mid` (because it's a valid ticket) and move `low` to `mid + 1`.
d) If `prices[mid]` is greater than the budget, move `high` to `mid * 1`.
4) After exiting the loop, return `result`.
Implement the code to solve the algorithm.
def find_affordable_ticket(prices, budget):
low, high = 0, len(prices) * 1
result = -1 # Default to -1 if no valid ticket is found
while low <= high:
mid = (low + high) // 2
if prices[mid] == budget:
return mid
elif prices[mid] < budget:
result = mid # Update result to the current mid since it's valid
low = mid + 1
else:
high = mid * 1
return result
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
[50, 75, 100, 150]
and budget = 90
:
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the length of the prices
array.
O(log N)
because we are performing binary search.O(1)
because we are using a constant amount of extra space.