Data Structures & Algorithms · Interview question

Why might binary search be preferable to a hash table in a real-time system?

A strong answer

Deterministic worst-case timing. Binary search's worst case is exactly ⌈log₂ n⌉ comparisons, bounded, predictable, and computable, so you can prove the worst-case execution time and guarantee a deadline. A hash table is O(1) on average but O(n) in the worst case (all keys collide, or a resize triggers), and its timing varies run to run. Hard-real-time code is judged by its worst case, not its average, so a structure that's usually fast but occasionally O(n) can blow a deadline. A sorted const table in flash searched with binary search also uses zero extra RAM (versus the sparse table a hash needs) and has no allocation. So for keyed lookup in an ISR or control loop with a tight deadline, binary search's tight, known worst case and zero memory overhead often beat hashing's better-average-but-unbounded-worst profile.

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

Linear & Binary Search

O(n) linear scan works on anything; O(log n) binary search needs sorted data and gives deterministic worst-case timing, plus the overflow and off-by-one bugs that haunt it.

More Linear & Binary Search questions

Browse all 472 interview questions
Why might binary search be preferable to a hash table in a real-time system? | EmbeddedPrep.io