GATE Computer ScienceHardGATE CS (PYQ pattern)

rot(a, n, k) does: reverse(a, 0, k-1); reverse(a, k, n-1); reverse(a, 0, n-1), where reverse(a, i, j) reverses a[i..j] in place. The array a = {1, 2, ..., 10} is passed to rot(a, 10, 7) and then to rot(a, 10, 6). What are a[0] and a[9] at the end?

  1. A. 8 and 7
  2. B. 4 and 3
  3. C. 1 and 10
  4. D. 5 and 4

Correct answer: B. 4 and 3

Reversing the two parts and then the whole array is a left rotation by k: for [1..7 | 8..10], reversing gives 7..1, 10 9 8, and the full reversal gives 8 9 10 1 ... 7. Two calls rotate left by 7 + 6 = 13, i.e. by 3 positions mod 10, giving 4 5 6 7 8 9 10 1 2 3: a[0] = 4, a[9] = 3. Reading it as a right rotation gives 8 and 7.

More Programming and Data Structures (GATE) questions

Exams that ask this topic