Queue Using Array - Problem

Implement a queue data structure using an array. Your implementation should support the following operations:

  • enqueue(item) - Add an element to the rear of the queue
  • dequeue() - Remove and return the front element from the queue
  • front() - Return the front element without removing it
  • isEmpty() - Check if the queue is empty
  • size() - Return the number of elements in the queue

You will be given a sequence of operations to perform on the queue. For each operation, you need to return the appropriate result or null if the operation is invalid (e.g., dequeue from empty queue).

Note: The queue should handle wrap-around when using a fixed-size array to maximize space efficiency.

Input & Output

Example 1 — Basic Queue Operations
$ Input: operations = [["enqueue",10],["enqueue",20],["front"],["dequeue"],["size"],["isEmpty"]]
Output: [null,null,10,10,1,false]
💡 Note: Enqueue 10 and 20 (returns null), front returns 10, dequeue returns and removes 10, size is 1, isEmpty is false
Example 2 — Empty Queue Operations
$ Input: operations = [["isEmpty"],["dequeue"],["front"],["size"]]
Output: [true,null,null,0]
💡 Note: Empty queue: isEmpty returns true, dequeue and front return null, size is 0
Example 3 — Mixed Operations
$ Input: operations = [["enqueue",5],["enqueue",15],["dequeue"],["enqueue",25],["front"],["size"]]
Output: [null,null,5,null,15,2]
💡 Note: Add 5,15; remove 5; add 25; front is 15; size is 2 (elements: 15,25)

Constraints

  • 1 ≤ operations.length ≤ 1000
  • Each operation is valid according to the queue interface
  • -104 ≤ element values ≤ 104

Visualization

Tap to expand
INPUT OPERATIONSCIRCULAR ARRAYRESULTSenqueue(10)enqueue(20)front()dequeue()1020frontrearnullnull1010Key Insight:Circular array with modulo arithmetic eliminates O(n) shifting operations,making all queue operations O(1) while maintaining FIFO order efficiently.TutorialsPoint - Queue Using Array | Circular Array Approach
Asked in
Amazon 35 Microsoft 28 Google 22 Apple 18
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen