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: heights = [[3,1,4,2,5]]
Output: [[2,1,2,1,0]]
EDGE CASE
Input: heights = [[5,1],[3,1],[4,1]]
Output: [[3,1],[2,1],[1,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.
Plan the solution with appropriate visualizations and pseudocode.
Maintain a stack and pop an element off
Increment answer by 1 when the current height is more than the top element on the stack.
โ ๏ธ Common Mistakes
Implement the code to solve the algorithm.
class Solution:
def seePeople(self, heights: List[List[int]]) -> List[List[int]]:
m, n = len(heights), len(heights[0])
ans = [[0] * n for _ in range(m)]
s = collections.deque() # a deque behave like mono-stack
for i in range(m): # look right
for j in range(n-1, -1, -1):
num = heights[i][j]
idx = bisect.bisect_left(s, num) # binary search on an increasing order sequence
ans[i][j] += idx + (idx < len(s)) # if `idx` is not out of bound, meaning the next element in `s` is the first one large than `num`, we can count it too
while s and s[0] <= num: # keep a mono-descreasing stack
s.popleft()
s.appendleft(num)
s.clear()
for j in range(n): # look below
for i in range(m-1, -1, -1):
num = heights[i][j]
idx = bisect.bisect_left(s, num)
ans[i][j] += idx + (idx < len(s))
while s and s[0] <= num:
s.popleft()
s.appendleft(num)
s.clear()
return ans
class Solution {
public int[][] seePeople(int[][] heights) {
int m = heights.length, n = heights[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < n; i++){ // DOWN
Deque<Integer> stack = new ArrayDeque<>();
for (int j = m - 1; j >= 0; j--){
while(!stack.isEmpty() && heights[j][i] > stack.peek()){
ans[j][i]++;
stack.pop();
}
if (!stack.isEmpty()){
ans[j][i]++;
}
if (stack.isEmpty() || heights[j][i] != stack.peek()){
stack.push(heights[j][i]);
}
}
}
for (int i = 0; i < m; i++){ // RIGHT
Deque<Integer> stack = new ArrayDeque<>();
for (int j = n - 1; j >= 0; j--){
while(!stack.isEmpty() && heights[i][j] > stack.peek()){
ans[i][j]++;
stack.pop();
}
if (!stack.isEmpty()){
ans[i][j]++;
}
if (stack.isEmpty() || heights[i][j] != stack.peek()){
stack.push(heights[i][j]);
}
}
}
return ans;
}
}
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.