Data Structures & AlgorithmsHardProduct company OA
A stack is built from two queues with a costly push: enqueue x into the empty queue Q2, move every element of Q1 into Q2 one by one, then swap the names Q1 and Q2. Counting each enqueue and each dequeue as one operation, how many operations does the 5th push cost (after four pushes and no pops)?
- A. 5
- B. 9
- C. 8
- D. 4
Correct answer: B. 9
Q1 holds 4 elements. The push does 1 enqueue of x plus, for each of the 4 old elements, 1 dequeue and 1 enqueue: 1 + 2·4 = 9. This keeps the newest element at the front of Q1, so pop is a single dequeue. '5' counts only enqueues; '8' forgets the enqueue of x.
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
- With at most k = 2 character replacements, what is the length of the longest substring of 'AABCABBB' that can be turned into a single…
- What is the length of the longest contiguous subarray of [0, 1, 1, 0, 1, 1, 1, 0, 0, 0] with an equal number of 0s and 1s? (Map 0 to −1…
- What is the maximum sum of a non-empty contiguous subarray of the CIRCULAR array [5, −8, 3, 4, −2, 6, −9, 7] (a subarray may wrap from the…
- What is the maximum product of a non-empty contiguous subarray of [2, −3, 0, −2, −4, 3, −1]?
- What is the next lexicographic permutation of [1, 5, 8, 4, 7, 6, 5, 3, 1]?
- Circular route: station i gives gas[i] and driving to station i + 1 costs cost[i], with gas = [3, 1, 5, 2, 6] and cost = [4, 3, 2, 4, 2]…