0
Challenge · 37Structures You Build Yourself
Queue and the shift() trap
Structuresused in ~90% of apps
The most expensive one-character mistake in JavaScript. `shift()` looks exactly like `pop()` and costs a thousand times more, and it is the single most common reason a correct BFS solution times out.
Core idea. A queue is first in, first out. You add at the back and take from the front. JavaScript has no queue, and the obvious way to fake one, `push` plus `shift`, quietly turns a linear algorithm into a quadratic one. The fix is to never remove from the front at all: keep an index.
poke it, drag it,
try to break it
try to break it
no slides here.
you drive.
you drive.
Playground, this isn't a screenshot
draining 200,000 items. Measured, not estimated
q.shift()3,861 msevery removal re-indexes the whole array
head++1 msnothing moves, only a number changes
Same algorithm, same answer, about four thousand times the running time. Nothing in the source code hints at it.
↑ play a little first, then dig in