How Queues Work — API Cheat Sheet
No exercise here — enqueue/dequeue across Java, C#, Python, and JavaScript/TypeScript, and the O(n) trap that catches people using the wrong structure.
This is a reference page, not a graded exercise. A queue is first-in-first-out (FIFO): the first thing you add is the first thing you remove. Reach for it for BFS traversals and anything modeled as "process in the order it arrived."
Java — Deque<T>
| Want to... | Method | Example |
|---|---|---|
| Create | new ArrayDeque<>() | Deque<Integer> queue = new ArrayDeque<>(); |
| Enqueue (add to back) | .offer(v) or .add(v) | |
| Dequeue (remove from front) | .poll() | returns null if empty; .remove() throws instead |
| Peek at front | .peek() | returns null if empty |
| Check empty | .isEmpty() |
C# — Queue<T>
| Want to... | Method | Example |
|---|---|---|
| Create | new Queue<T>() | var queue = new Queue<int>(); |
| Enqueue | .Enqueue(v) | |
| Dequeue | .Dequeue() | throws if empty |
| Peek | .Peek() | throws if empty — check .Count first |
| Size | .Count | property |
Python — collections.deque, not list
| Want to... | Method | Example |
|---|---|---|
| Create | deque() | from collections import deque; q = deque() |
| Enqueue (add to back) | .append(v) | |
| Dequeue (remove from front) | .popleft() | O(1) — this is the whole reason to use deque |
| Peek at front | q[0] | |
| Don't use | list.pop(0) | works, but is O(n) — a plain list has to shift every remaining element down by one |
JavaScript / TypeScript — Array, with a caveat
| Want to... | Method | Example |
|---|---|---|
| Enqueue (add to back) | .push(v) | O(1) |
| Dequeue (remove from front) | .shift() | O(n) — every remaining element has to be re-indexed |
| Peek at front | arr[0] | |
| Faster alternative | keep a startIndex pointer instead of .shift()-ing, or use an array-backed circular buffer, when performance actually matters | JS has no built-in O(1)-dequeue structure the way Python has deque |
The gotcha that costs the most time: it's tempting to reach for a plain list/array as a queue in Python and JS, and it works correctly — but .pop(0)/.shift() are O(n), silently turning an O(n) BFS into O(n^2). Use collections.deque in Python; in JS/TS, know that .shift() has this cost so you can justify it (or avoid it) if asked about complexity.
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
This question doesn't have a code exercise.