Data Structures & AlgorithmsHardTCS NQT · Product Company SDE

Problem: The array [4, 9, 2, 7, 5, 6] is processed by insertion sort (standard insertion into the sorted prefix, shifting larger elements right). How many element shifts (moves of an element one position to the right) occur in total?

  1. A. 11
  2. B. 6
  3. C. 15
  4. D. 7

Correct answer: D. 7

Shifts equal inversions: (4,2), (9,2), (9,7), (9,5), (9,6), (7,5), (7,6) = 7. Counting comparisons instead of shifts gives 11, missing one inversion gives 6, and 15 is the worst case C(6, 2).

More Coding Interview Problems questions

Exams that ask this topic