Data Structures & AlgorithmsHardProduct-company MCQ pattern
A queue is built from two stacks: enqueue pushes onto stack IN; dequeue pops from stack OUT, first moving everything from IN to OUT only when OUT is empty. What is the amortised cost per operation over any sequence of n operations?
- A. O(√n)
- B. O(n)
- C. O(log n)
- D. O(1)
Correct answer: D. O(1)
Each element is pushed to IN once, moved to OUT once and popped once, so n operations do O(n) work in total: O(1) amortised. A single dequeue can still cost O(n) in the worst case.
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
- An array has only 0s, 1s and 2s. The Dutch National Flag algorithm sorts it in one pass. What are its time and extra space?
- n integers, each in the range 0 to n² − 1, must be sorted. Which approach sorts them in O(n) time?
- How many comparisons does top-down merge sort (split in halves, stop comparing when one side runs out) make on [5, 1, 7, 3, 20, 15, 30, 25]?
- 1800 keys are stored in a hash table with 600 slots using separate chaining and simple uniform hashing. About how many key comparisons…
- How many distinct non-empty substrings does the string ABAB have?
- What is the KMP failure (LPS) array for the pattern AABAACAABAA?