Stacks and Queues · Coding problem
Implement Queue using Arrays
A free coding problem from the Array-Backed Stack and Queue skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
Implement a fixed-capacity queue backed by a plain array (a circular buffer; in Python, a list preallocated with [0] * capacity), supporting:
enqueue(x)- add a value to the back.dequeue()- remove and return the front value, or-1if empty.
Input format
Line 1: capacity. Line 2: q, the number of operations. Each of the next q lines is ENQUEUE x or DEQUEUE. For each DEQUEUE, print the result.
Example
Input:
3
5
ENQUEUE 1
ENQUEUE 2
ENQUEUE 3
DEQUEUE
ENQUEUE 4
Output:
1
After dequeuing 1, there's room to enqueue 4 even though the array only has capacity 3 - the freed slot at the front is reused.
Constraints
1 <= capacity <= 10^41 <= q <= 10^40 <= x <= 10^9, so the empty result-1never collides with a stored value- The queue never holds more than
capacityelements at once
How it's graded
- Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Array-Backed Stack and Queue
Solve it Implement Queue using Arrays free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime