Data Structures & Algorithms · Interview question

What does "peek" do, and why does the distinction from "pop" matter?

A strong answer

peek (or top/front) returns the next element to be removed without removing it; pop/dequeue removes and returns it. The distinction matters because many algorithms need to inspect the next item to decide what to do before committing to removing it, for example, in expression parsing you peek at the operator on top of the stack to compare precedence before deciding whether to pop it. If you accidentally pop when you meant to peek, you mutate the structure and lose an element you may still need, corrupting the sequence; conversely, peeking when you needed to consume leaves the item in place and you loop forever or reprocess it. Both should also handle the empty case (return false / a sentinel) rather than reading past the top, which on fixed memory is an out-of-bounds read.

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

Browse all 472 interview questions
What does "peek" do, and why does the distinction from "pop" matter? | EmbeddedPrep.io