Skip to content
Onsite

Implement Queue

EasyP2Coding

Implement a queue of integers (first in, first out) in which every operation takes O(1) amortized time.

Implement the MyQueue class:

  • MyQueue() creates an empty queue.
  • enqueue(x) adds x at the back.
  • dequeue() removes and returns the front element, or -1 if the queue is empty.
  • front() returns the front element without removing it, or -1 if the queue is empty.
  • isEmpty() returns true if the queue has no elements.
  • size() returns the number of elements.

Removing from the front of an array with shift() or pop(0) is O(n), so it does not meet the requirement.

Example 1

Input
["MyQueue","enqueue","enqueue","front","dequeue","dequeue","isEmpty"] [[],[1],[2],[],[],[],[]]
Output
[null,null,null,1,1,2,true]
Why
Elements leave in the order they arrived.

Constraints

  • -10^9 <= x <= 10^9
  • At most 10^5 calls in total.

Hints

Run checks the 2 visible tests, Submit all 7.