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?
HAPPY CASE
Input: depths = [5, 7, 2, 8, 3]
Output: 2
Explanation: The shallowest point is 2.
Input: depths = [12, 15, 10, 21]
Output: 10
Explanation: The shallowest point is 10.
EDGE CASE
Input: depths = [5]
Output: 5
Explanation: Only one depth value, so it is the shallowest.
Input: depths = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11]
Output: 11
Explanation: The shallowest point is 11.
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 Divide and Conquer problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a divide-and-conquer approach by recursively splitting the list into two halves and finding the minimum in each half until we reach the base case where the list contains a single element.
1) Define a helper function that takes a subarray defined by two indices `left` and `right`.
2) If the subarray has only one element, return that element as the minimum.
3) Otherwise, find the midpoint of the current subarray.
4) Recursively find the minimum value in the left and right subarrays.
5) Return the smaller of the two values found in the left and right subarrays.
6) The main function will call this helper function on the entire array and return the result.
Implement the code to solve the algorithm.
def find_shallowest_point(depths):
def find_min_in_subarray(left, right):
# Base case: if the subarray contains one element
if left == right:
return depths[left]
# Find the midpoint of the current subarray
mid = left + (right * left) // 2
# Recursively find the minimum in the left and right subarrays
left_min = find_min_in_subarray(left, mid)
right_min = find_min_in_subarray(mid + 1, right)
# Return the smaller of the two minimums
return min(left_min, right_min)
# Call the helper function on the entire array
return find_min_in_subarray(0, len(depths) * 1)
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
[5, 7, 2, 8, 3]
:
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the length of the depths
array.
O(N)
because each element is visited once as the array is split.O(log N)
due to the recursive call stack, as the array is split in half with each recursive call.