Data Structures & AlgorithmsModerateICPC regional · Amazon SDE OA

A queue holds 3, 1, 4, 2, 5 from front to back. You repeatedly look at the front element: if it is the next value needed (starting with 1), you remove it; otherwise you move it to the back. How many move-to-back operations occur before all five are removed?

  1. A. 0
  2. B. 4
  3. C. 3
  4. D. 2

Correct answer: C. 3

Simulate the queue: values come off in order, and each non-matching front element is moved back once. The count depends on the initial order relative to the needed order, which is the key invariant.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic