Data Structures & AlgorithmsHardAmazon/Microsoft SDE pattern

Array [1, 2, 3, 4, 5, 6, 7, 8, 9] is left-rotated by d = 6 positions using the reversal algorithm (reverse first d, reverse rest, reverse whole). What is the result?

  1. A. 7, 8, 9, 1, 2, 3, 4, 5, 6
  2. B. 9, 8, 7, 6, 5, 4, 3, 2, 1
  3. C. 8, 9, 1, 2, 3, 4, 5, 6, 7
  4. D. 4, 5, 6, 7, 8, 9, 1, 2, 3

Correct answer: A. 7, 8, 9, 1, 2, 3, 4, 5, 6

Left-rotating by d moves the first d elements to the end in order: reversing the first d elements, then the remaining n−d, then the whole array achieves this in O(n) time with O(1) extra space, giving [7, 8, 9, 1, 2, 3, 4, 5, 6]. Rotating right by d instead would give [4, 5, 6, 7, 8, 9, 1, 2, 3].

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

Exams that ask this topic