Machine-translated by Google. Questions are authored in English.
Top

Discussion

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 O(1) time MIN operation that returns a pointer to the record with smallest key present in the stack
1) without deleting the corresponding record, and
2) without increasing the complexities of the standard stack operations.

Which one or more of the following approach(es) can achieve it?

  • A.Keep with every record in the stack, a pointer to the record with the smallest key below it.
  • B.Keep a pointer to the record with the smallest key in the stack.
  • C.Keep an auxiliary array in which the key values of the records in the stack are maintained in sorted order.
  • D.Keep a Min-Heap in which the key values of the records in the stack are maintained.

Answer: A

Only keeping, with every record, a pointer to the record with the smallest key below it works.

On PUSH, compare the new key with the minimum stored in the current top record and save a pointer to whichever is smaller (the new record itself if it is smaller): O(1). On POP, simply discard the top record; the record beneath already holds the minimum of everything below it. MIN reads the top record's pointer: O(1). No standard operation becomes slower.

A single pointer to the minimum fails when the minimum is popped: finding the new minimum then needs a scan of the stack, O(n). A sorted auxiliary array makes PUSH and POP O(n), since an element must be inserted or removed in the middle. A min-heap gives O(1) MIN but makes PUSH and POP O(log n), increasing their complexity.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.