Data Structures & AlgorithmsHard
A min-stack stores a pair (value, current minimum) per entry. Why does popping never require recomputing the minimum?
- A. Because the minimum of the stack below an entry is already stored with that entry, so popping restores the previous minimum directly.
- B. Because the minimum is always the most recently pushed value.
- C. Because pop only ever removes the minimum element.
- D. Because the stack is kept sorted at all times.
Correct answer: A. Because the minimum of the stack below an entry is already stored with that entry, so popping restores the previous minimum directly.
Each entry records the minimum of everything at or below it, so the stack below always carries its own correct minimum. Popping simply exposes the entry beneath, with no scan needed.
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
- In the 'remove nodes with a greater value to their right' problem, which list order is processed to decide survivors in O(n)?
- In the asteroid collision problem, why does a stack of right-moving asteroids suffice?
- A linear-time check decides whether a permutation can be sorted by one stack. Which property is equivalent to being stack-sortable?
- In the jump game (minimum number of jumps), why does a single left-to-right scan with a 'current boundary' count the jumps correctly?
- In the 'first non-repeating character in a stream' problem, why is a queue with lazy removal used?
- Why is a hash map (not a sorted array) used to find the longest run of consecutive integers in an unsorted array in linear expected time?