easyQueue 0 views

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...MethodExample
Createnew 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...MethodExample
Createnew Queue<T>()var queue = new Queue<int>();
Enqueue.Enqueue(v)
Dequeue.Dequeue()throws if empty
Peek.Peek()throws if empty — check .Count first
Size.Countproperty

Python — collections.deque, not list

Want to...MethodExample
Createdeque()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 frontq[0]
Don't uselist.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...MethodExample
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 frontarr[0]
Faster alternativekeep a startIndex pointer instead of .shift()-ing, or use an array-backed circular buffer, when performance actually mattersJS 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.