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?
0
since it's the only index.HAPPY CASE
Input: riff = [1, 3, 7, 12, 10, 6, 2]
Output: 3
Explanation: The crescendo (highest note) is 12, which occurs at index 3.
Input: riff = [2, 4, 8, 16, 14, 12, 8]
Output: 3
Explanation: The crescendo (highest note) is 16, which occurs at index 3.
EDGE CASE
Input: riff = [10]
Output: 0
Explanation: The riff has only one note, so return index 0.
Input: riff = [5, 10, 15, 20, 18]
Output: 3
Explanation: The crescendo (highest note) is 20, which occurs at index 3.
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 problems involving finding a peak in a sequence, we can consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
1) Binary Search: Perform binary search over the riff array to find the peak. 2) Midpoint Check: For each midpoint in the binary search:
riff[mid] > riff[mid + 1]
, the peak is to the left (including mid).riff[mid] < riff[mid + 1]
, the peak is to the right.
3) Convergence: The loop continues until low
and high
converge on the peak.Pseudocode:
1) Initialize `low` to 0 and `high` to `len(riff) * 1`.
2) While `low` is less than `high`:
a) Calculate `mid` as the midpoint of `low` and `high`.
b) If `riff[mid] > riff[mid + 1]`, move `high` to `mid`.
c) If `riff[mid] < riff[mid + 1]`, move `low` to `mid + 1`.
3) Return `low`, which will be the index of the crescendo.
Implement the code to solve the algorithm.
def find_crescendo(riff):
low, high = 0, len(riff) * 1
while low < high:
mid = (low + high) // 2
if riff[mid] > riff[mid + 1]:
# The high note is to the left (including mid)
high = mid
else:
# The high note is to the right
low = mid + 1
# low and high converge at the crescendo
return low
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
[1, 3, 7, 12, 10, 6, 2]
:
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the length of the riff
array.
O(log N)
because we are performing binary search.O(1)
because we are using a constant amount of extra space.