Constant-Time Range Queries and Stack with Maximum Tracking
Data Structure DesignModel answerLast 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 indexleftthroughright(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 elementxto the toppop()— remove and return the top elementtop()— return the top element without removing itpeekMax()— return the maximum elementpopMax()— 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This problem tests two fundamental patterns in data structure design: preprocessing for query optimization and maintaining multiple views of the same data with lazy synchronization.
Part 1: Interval Sum Data Structure
Approach
The core insight is to precompute cumulative sums during construction. Build an auxiliary array where each position stores the sum of all elements up to that point. Any interval sum then becomes a simple subtraction.
Create an array cumulative of length n + 1 where cumulative[i] represents the sum of the first i elements. Initialize cumulative[0] = 0 as a sentinel. For each subsequent position: cumulative[i + 1] = cumulative[i] + nums[i].
To answer sumRange(left, right), return cumulative[right + 1] - cumulative[left]. This works because cumulative[right + 1] includes all elements from index 0 through right, and subtracting cumulative[left] removes elements 0 through left - 1, leaving exactly the elements from left through right.
The sentinel zero at position 0 elegantly handles the edge case where left = 0 without special conditionals.
Complexity
- Construction: O(n) time to build the cumulative array, O(n) space to store it
- Query: O(1) time per query, O(1) additional space
With q queries, the total cost is O(n + q) versus O(nq) for recomputing each range sum naively.
Edge Cases
- Single-element ranges where
left == rightwork correctly - Negative numbers are handled naturally by the arithmetic
- Empty input arrays are valid; no queries would be valid on them
Implementation
class IntervalSumQuery:
def __init__(self, nums):
n = len(nums)
self.cumulative = [0] * (n + 1)
for i in range(n):
self.cumulative[i + 1] = self.cumulative[i] + nums[i]
def sumRange(self, left, right):
return self.cumulative[right + 1] - self.cumulative[left]
Part 2: Maximum-Tracking Stack
Approach
The challenge is that popMax removes an element from an arbitrary position, not just the top. A standard stack with auxiliary max-tracking can handle peekMax in O(1), but popMax would require O(n) to reconstruct the stack after removing the middle element.
The efficient solution maintains two synchronized views of the same elements using lazy deletion:
- Stack view: A list storing
(value, id)pairs preserving insertion order - Heap view: A max-heap storing
(-value, -id)to efficiently find the maximum. Values are negated to create a max-heap from Python's min-heap. IDs are negated so that among equal values, the most recent (largest ID) appears first, matching the "topmost max" requirement. - Deletion set: When an element is removed through one view, record its unique ID. Before accessing the top of either structure, discard entries whose IDs are in the deletion set.
Each pushed element receives a unique, monotonically increasing ID. This prevents ID collisions and ensures proper ordering.
Why This Works
Every live element exists in exactly both structures. When we need the stack top or heap top, we first clean stale entries—those marked as deleted. After cleanup:
- The stack top is the most recently pushed live element
- The heap top is the live element with maximum value (and largest ID among ties)
The lazy deletion strategy defers physical removal until the stale entry reaches the top of a structure, amortizing the cleanup cost.
Complexity
push: O(log n) for heap insertionpopandtop: Amortized O(1). Each element is popped from the stack at most once.popMaxandpeekMax: Amortized O(log n). Each element is popped from the heap at most once.- Space: O(n) for all structures combined
The amortization argument: each element enters each structure once, so it can be lazily cleaned at most once from each structure.
Alternative Approach
Use a doubly-linked list for stack order plus a balanced binary search tree mapping values to their nodes. This gives strict O(log n) per operation without amortization, but requires more complex implementation. In Python, this would need a third-party SortedList. The heap approach is cleaner with standard library tools.
Edge Cases
- Duplicate maxima: Must remove the most recent occurrence—the heap's negated IDs ensure this
- Interleaved operations: An element removed by
popMaxmust not reappear in subsequentpoportopcalls - All negative values: Work correctly with negated heap keys
Implementation
import heapq
class MaxTrackingStack:
def __init__(self):
self.stack = []
self.heap = []
self.deleted = set()
self.next_id = 0
def push(self, x):
pair = (x, self.next_id)
self.stack.append(pair)
heapq.heappush(self.heap, (-x, -self.next_id))
self.next_id += 1
def _cleanup_stack(self):
while self.stack and self.stack[-1][1] in self.deleted:
self.stack.pop()
def _cleanup_heap(self):
while self.heap and -self.heap[0][1] in self.deleted:
heapq.heappop(self.heap)
def pop(self):
self._cleanup_stack()
val, elem_id = self.stack.pop()
self.deleted.add(elem_id)
return val
def top(self):
self._cleanup_stack()
return self.stack[-1][0]
def peekMax(self):
self._cleanup_heap()
return -self.heap[0][0]
def popMax(self):
self._cleanup_heap()
neg_val, neg_id = heapq.heappop(self.heap)
self.deleted.add(-neg_id)
return -neg_val
Example Trace
For operations: push(5), push(1), push(5), top(), popMax(), top(), peekMax(), pop(), top()
- After three pushes: stack has [(5,0), (1,1), (5,2)], heap has [(-5,-2), (-5,-0), (-1,-1)]
top()returns 5 (value from ID 2)popMax()pops (-5,-2) from heap, marks ID 2 as deleted, returns 5top()cleans ID 2 from stack, returns 1 (value from ID 1)peekMax()returns 5 (from ID 0, now heap top after cleaning)pop()removes (1,1), marks ID 1 as deleted, returns 1top()returns 5 (only ID 0 remains)
Common Mistakes
- Part 1: Using 1-based indexing inconsistently, causing off-by-one errors in the subtraction
- Part 2: Forgetting to negate IDs in the heap, causing wrong max selection among duplicates
- Part 2: Cleaning only one structure, leading to stale data poisoning results
- Part 2: Not using unique IDs, making it impossible to distinguish between duplicate values