Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the largest rectangle that fits under a histogram of bar heights.
Problem: Find the largest rectangle that fits under a histogram of bar heights.
def largest(h):
st, best = [], 0
for i, x in enumerate(h + [0]):
while st and h[st[-1]] >= x:
height = h[st.pop()]
left = st[-1] + 1 if st else 0
best = max(best, height * (i - left))
st.append(i)
return best
print(largest([2, 1, 5, 6, 2, 3]), largest([3, 3, 3]))What is printed?- A. 10 9
- B. 12 9
- C. 10 3
- D. 6 9
Correct answer: A. 10 9
When a bar is popped, the bar now on top is its first smaller bar on the left and i is the first smaller on the right, so its widest rectangle is known. 5 and 6 together give 5 × 2 = 10. The appended 0 flushes the stack at the end – without it [3, 3, 3] would return 0. O(n).
More Coding Interview Problems questions
- Problem: Evaluate an expression in Reverse Polish notation; division truncates toward zero. python def rpn(tokens): st = [] for t in…
- Problem: Simulate asteroids on a line: positive moves right, negative left; on collision the smaller explodes, equal sizes both explode…
- Problem: Remove k digits from a number string to make the smallest possible number (no leading zeros in the result, "0" if empty). python…
- Problem: Design a stack that returns its minimum in O(1). The implementation below stores pairs. python st = [] def push(x): st.append((x…
- Problem: Return the first index whose value is ≥ x in a sorted array (n if none). cpp int lowerBound(vector<int>& a, int x) { int lo = 0…
- Problem: Count how many times a value occurs in a sorted array in O(log n). python from bisect import bisectleft, bisectright a = [2, 4…