Problem · Stack

Implement a Queue Using Two Stacks

Learn this problem
EasyOraclePHONE SCREEN

Problem statement

Process a sequence of queue operations while using exactly two stacks as the queue's storage. Do not use a queue data structure.

The arrays operations and values have the same length. At position i:

  • push adds values[i] to the back of the queue and produces no output.
  • pop removes the front value and appends its decimal string to the result.
  • peek reads the front value without removing it and appends its decimal string to the result.
  • empty appends true or false to the result.

Every pop or peek operation occurs while the queue is non-empty. Return the recorded outputs in operation order.

Function

processQueueOperations(operations: String[], values: int[]) → String[]

Examples

Example 1

operations = ["push","push","peek","pop","empty"]values = [1,2,0,0,0]return = ["1","1","false"]

After pushing 1 and 2, both peek and pop observe the front value 1. Value 2 remains, so the queue is not empty.

Example 2

operations = ["empty","push","empty","peek","pop","empty"]values = [0,7,0,0,0,0]return = ["true","false","7","7","true"]

The queue starts empty. After pushing 7, it is non-empty; peek and pop both return 7, after which it is empty again.

Example 3

operations = ["push","push","pop","push","peek","pop","pop","empty"]values = [-1,-2,0,3,0,0,0,0]return = ["-1","-2","-2","3","true"]

The first pop removes -1. Pushing 3 does not move it ahead of -2, so the next peek and pop return -2. The final pop returns 3.

More Oracle problems

drafts saved locally
public String[] processQueueOperations(String[] operations, int[] values) {
    // write your code here
}
operations["push","push","peek","pop","empty"]
values[1,2,0,0,0]
expected["1", "1", "false"]
checking account