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: [1,8,6,2,5,4,8,3,7]
Output: 49 (The max area is between index 1 and 8 with a
minimum height of 7, giving us a container of 7 by 7, which is 49)
Input: [1,1]
Output: 1
EDGE CASE
Input:[0,0]
Output: 0
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 Array/Strings, common solution patterns include:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use the two pointer solution, we start at the max width and reduce the width while maintaining the max height for each width, then we can find the maximum area at each width.
1. Create largest range, by creating a left and right pointer
2. At every part of the range calculate the current area at this width and check against our max area
a. Reduce the range/width while maintaining the maximum height
3. Return max area found
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Solution:
def maxArea(self, height: List[int]) -> int:
# Create largest range, by creating a left and right pointer
l, r = 0, len(height) - 1
maxArea = 0
# At every part of the range calculate the current area at this width and check against our max area
while l < r:
width = r - l
minHeight = min(height[l], height[r])
currArea = minHeight * width
maxArea = max(maxArea, currArea)
# Reduce the range/width while maintaining the maximum height
if height[l] < height[r]:
l += 1
else:
r -= 1
# Return max area found
return maxArea
class Solution {
public int maxArea(int[] height) {
// Create largest range, by creating a left and right pointer
int left = 0;
int right = height.length - 1;
int max = 0;
// At every part of the range calculate the current area at this width and check against our max area
while(left < right){
int w = right - left;
int h = Math.min(height[left], height[right]);
int area = h * w;
max = Math.max(max, area);
//Reduce the range/width while maintaining the maximum height
if(height[left] < height[right]) left++;
else if(height[left] > height[right]) right--;
else {
left++;
right--;
}
}
//Return max area found
return max;
}
}
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N represents the number of heights in array.
O(N)
, because we need to check the entire range of heights once. O(1)
, because we only use a constant number of variable to hold our area information.