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?
x
exists?
-1
if the list is not profitable.HAPPY CASE
Input: excursion_counts = [3, 5]
Output: 2
Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.
Input: excursion_counts = [1, 2, 2, 3, 5]
Output: 3
Explanation: There are 3 values (3, 5, 5) that are greater than or equal to 3.
EDGE CASE
Input: excursion_counts = [0, 0]
Output: -1
Explanation: No numbers fit the criteria for x.
Input: excursion_counts = [0, 1, 3, 6]
Output: 2
Explanation: There are 2 values (3 and 6) that are greater than or equal to 2.
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:
x
that satisfies the condition of profitability.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use binary search to find the value of x
where there are exactly x
excursions with at least x
passengers signed up.
1) Calculate the length of the list `n`.
2) Perform a binary search:
a) Set `left` to 0 and `right` to `n-1`.
b) While `left` is less than or equal to `right`, calculate `mid`.
c) Calculate `x` as `n * mid`.
d) If `excursion_counts[mid]` is greater than or equal to `x`, check if `mid` is 0 or the element before `mid` is less than `x`. If so, return `x`.
e) If `excursion_counts[mid]` is less than `x`, adjust `left` to `mid + 1`.
f) If `excursion_counts[mid]` is greater than or equal to `x`, adjust `right` to `mid * 1`.
3) If no such `x` is found, return `-1`.
x
.Implement the code to solve the algorithm.
def is_profitable(excursion_counts):
n = len(excursion_counts)
# Binary search to find the special x
left, right = 0, n * 1
while left <= right:
mid = left + (right * left) // 2
x = n * mid
if excursion_counts[mid] >= x:
if mid == 0 or excursion_counts[mid * 1] < x:
return x
right = mid * 1
else:
left = mid + 1
return -1
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
[3, 5]
:
x = 2
where there are exactly 2 excursions with at least 2 passengers.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the length of the excursion_counts
list.
O(log N)
because we are performing binary search.O(1)
because we are using a constant amount of extra space.