Consider a stack data structure into which we can PUSH and POP records. Assume that each record pushed in the stack has a positive integer key and that all keys are distinct.
We wish to augment the stack data structure with an time MIN operation that returns a pointer to the record with smallest key present in the stack
- without deleting the corresponding record, and
- without increasing the complexities of the standard stack operations.
Which one or more of the following approach(es) can achieve it?
View worked solution
Answer: A
To achieve an time complexity for the MIN operation without increasing the time complexity of the standard stack operations (PUSH and POP), we must ensure that both insertions and deletions can update the minimum tracking information in time.
Analyzing the Options:
-
Option A: Keep with every record in the stack, a pointer to the record with the smallest key below it (including itself).
- PUSH Operation: When pushing a new record , we compare its key with the key of the minimum element of the stack prior to this push (which is pointed to by the previous top element's pointer). The minimum for is the smaller of the two. This requires only time.
- POP Operation: When popping the top element, we simply remove it. The next element below it already contains the correct pointer to the minimum of the remaining stack. No updates to other elements are needed, taking time.
- MIN Operation: We simply return the pointer stored in the current top element of the stack. This takes time.
-
Option B: Keep a single pointer to the record with the smallest key in the stack.
- If the current minimum element is popped, we lose the reference to the next minimum element. To find the new minimum, we would have to scan the entire stack, which takes time. This increases the complexity of the
POPoperation.
- If the current minimum element is popped, we lose the reference to the next minimum element. To find the new minimum, we would have to scan the entire stack, which takes time. This increases the complexity of the
-
Option C: Keep an auxiliary array in sorted order.
- Maintaining a sorted array requires time for insertion (during
PUSH) or deletion (duringPOP) to shift elements. This increases the complexity of standard stack operations.
- Maintaining a sorted array requires time for insertion (during
-
Option D: Keep a Min-Heap.
- Inserting into or deleting from a Min-Heap takes time. This increases the complexity of
PUSHandPOPoperations from to .
- Inserting into or deleting from a Min-Heap takes time. This increases the complexity of
Hence, only Option A satisfies all the given conditions.
Free practice · Your answers on this page are not saved.
