Use a ring buffer: a fixed array with head and tail indices that wrap, giving O(1) enqueue at the back and O(1) dequeue from the front with no element ever moving. The naive mistake is implementing the queue as a plain array where you enqueue at the end and dequeue by removing a[0] and shifting every remaining element down one, that makes each dequeue O(n), which is catastrophic in a hot path like a UART handler dequeuing per byte. The shift is pure waste: the data doesn't need to move, only your notion of "where the front is." The ring buffer captures that by advancing the tail index instead of moving data. So: a queue is a ring buffer; never a shifting array.
Data Structures & Algorithms · Interview question
How would you implement a queue efficiently, and what's the naive mistake?
A strong answer
What a weak answer sounds like
You know the answer. Do you know what gets you dinged?
Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.
From the lesson
Stacks & Queues
LIFO stacks and FIFO queues: the two access disciplines behind the call stack, expression evaluation, and ISR-to-main event passing, and how to back each with fixed memory.
More Stacks & Queues questions
What's the difference between a stack and a queue?Give a concrete embedded use for a stack and one for a queue.What does "peek" do, and why does the distinction from "pop" matter?What bounds must you check on a fixed-capacity stack or queue?An ISR enqueues bytes into a ring-buffer queue and the main loop dequeues them. Do you need a lock?How would you implement a FIFO queue using only two stacks, and what's the cost?
Browse all 472 interview questions