Data Structures & AlgorithmsVery hardProduct company OA
Largest rectangle under a histogram using a stack of (start index, height). What is printed?
Largest rectangle under a histogram using a stack of (start index, height). What is printed?
def rect(h):
st, best = [], 0
for i, x in enumerate(h + [0]):
start = i
while st and st[-1][1] >= x:
j, y = st.pop()
best = max(best, y * (i - j)); start = j
st.append((start, x))
return best
print(rect([2, 4, 4, 1, 5, 6, 2, 3]), rect([3, 3, 3, 3]), rect([1, 2, 3, 4, 5]))- A. 12 12 15
- B. 10 12 9
- C. 10 16 9
- D. 8 12 9
Correct answer: B. 10 12 9
When a bar is popped, the current index is the first bar to its right that is lower, and the stored start already extends left over all taller bars it replaced, so its rectangle is height × (i − start). The sentinel 0 flushes the stack. [2,4,4,1,5,6,2,3]: best is 5 × 2 = 10 (bars 5, 6); 4 × 2 = 8, 1 × 8 = 8, 2 × 4 = 8. [3,3,3,3]: 12. [1,2,3,4,5]: 3 × 3 = 9. The answer 15 adds the bars instead of taking the minimum height. O(n) total.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Rain water trapped between bars, computed with two pointers. What is printed? python def water(h): l, r, lm, rm, w = 0, len(h) - 1, 0, 0…
- Next greater element in a CIRCULAR array (scan the array twice, pushing indices only in the first pass). What is printed? python def…
- Towers stand in a row. Two towers can see each other if every tower strictly between them is shorter than both. The function counts such…
- A ticket number may lose exactly k digits; the remaining digits must keep their order and form the smallest possible number (leading zeros…
- Count subarrays whose sum is divisible by 3 using prefix sums and a remainder map. The second version imitates C's % operator (sign…
- Longest subarray with sum exactly 5 when the array contains NEGATIVE numbers: a shrink-when-too-big sliding window versus a prefix-sum map…