KatInterview

Constant-Time Range Queries and Stack with Maximum Tracking

Data Structure DesignModel answer
MediumModel answerData Structure Designprefix-sumstackheap

Last updated

Implement two data structures: one supporting fast interval sum queries on a fixed array, and a stack that efficiently tracks and removes its maximum element.

You need to implement two independent data structures that demonstrate efficient auxiliary state management.

Part 1: Interval Sum Data Structure

Design a class that supports fast sum queries over fixed ranges of an integer array.

Your class should support:

  • Constructor that accepts an integer array
  • sumRange(left, right) that returns the sum of elements from index left through right (inclusive)

The input array will not change after construction, and you may receive many range queries.

Example:

arr = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) → 1  (because -2 + 0 + 3 = 1)
sumRange(2, 5) → -1 (because 3 + (-5) + 2 + (-1) = -1)
sumRange(0, 5) → -3

Part 2: Maximum-Tracking Stack

Design a stack data structure that can efficiently retrieve and remove its maximum element.

Your stack should support:

  • push(x) — add element x to the top
  • pop() — remove and return the top element
  • top() — return the top element without removing it
  • peekMax() — return the maximum element
  • popMax() — remove and return the maximum element

When multiple elements share the maximum value, popMax() should remove the one closest to the top of the stack.

All operations are called on non-empty stacks only.

Example:

push(5), push(1), push(5)
top() → 5
popMax() → 5  (removes the second 5, which is topmost)
top() → 1
peekMax() → 5  (the first 5 remains)
pop() → 1
top() → 5

For both problems, describe your approach, analyze time and space complexity, and provide working implementations.

Hints

Hint 1

For interval sums on immutable data, consider what you can compute once during construction to make each query trivial.

Hint 2

The maximum-tracking stack needs to maintain two different orderings simultaneously—how can you keep both views synchronized?

Hint 3

When removing an element from the middle of one ordering, you can mark it as deleted rather than physically removing it from both structures immediately.