Data Structures & Algorithms · Interview question

Why use a power-of-two capacity?

A strong answer

So the wrap-around can use a bitwise AND instead of a modulo. Advancing an index is head = (head + 1) % CAP, and % is integer division, which is multiple cycles, or very slow, on MCUs without a hardware divider (e.g. Cortex-M0/M0+). If CAP is a power of two, x % CAP equals x & (CAP - 1) for non-negative x, and the AND is a single cycle. So head = (head + 1) & (CAP - 1) is the fast, division-free wrap, which matters in a hot path like a per-byte UART ISR. That's why production ring buffers almost always pick capacities like 16, 64, or 256. The minor cost is you can't size the buffer to an arbitrary number, but rounding up to the next power of two is usually fine.

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

Ring Buffers

The fixed-memory FIFO behind every UART driver: head and tail indices wrapping a static array, O(1) push/pop, and the full-vs-empty trick, plus the lock-free single-producer/consumer pattern.

More Ring Buffers questions

Browse all 472 interview questions
Why use a power-of-two capacity? | EmbeddedPrep.io