Skip to content
Official PYQ · 2000

GATE CS 2000 Q2.15 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Suppose you are given an array s[1....n]s[1....n] and a procedure reverse (s,i,j)(s, i, j) which reverses the order of elements in ss between positions ii and jj (both inclusive). What does the following sequence do, where 1⩽k⩽n1 \leqslant k \leqslant n:

           reverse (s, 1, k);
           reverse (s, k+1, n);
           reverse (s, 1, n);
Choose one option
View worked solution

Answer: A

To understand the effect of the given sequence of operations, let us represent the array s[1…n]s[1…n] as the concatenation of two subarrays, AA and BB:

  • A=s[1…k]A = s[1…k] of length kk
  • B=s[k+1…n]B = s[k+1…n] of length n−kn-k

Thus, the initial array is s=ABs = AB.

Let XRX^R denote the reversal of a sequence XX. Let's trace the operations step-by-step:

  1. reverse(s, 1, k): Reverses the first kk elements (subarray AA).
    The array becomes: ARBA^R B
  2. reverse(s, k+1, n): Reverses the remaining n−kn-k elements (subarray BB).
    The array becomes: ARBRA^R B^R
  3. reverse(s, 1, n): Reverses the entire array.
    The reversal of the concatenated sequence ARBRA^R B^R is: (ARBR)R=(BR)R(AR)R=BA(A^R B^R)^R = (B^R)^R (A^R)^R = BA The array becomes: BABA

Since the initial array ABAB has been transformed into BABA, the first kk elements have moved to the end, and the remaining elements have shifted to the front. This is precisely a left rotation of ss by kk positions.

Example:

Let s=[1,2,3,4,5]s = [1, 2, 3, 4, 5] with n=5n = 5 and k=2k = 2.

  • After reverse(s, 1, 2): s=[2,1,3,4,5]s = [2, 1, 3, 4, 5]
  • After reverse(s, 3, 5): s=[2,1,5,4,3]s = [2, 1, 5, 4, 3]
  • After reverse(s, 1, 5): s=[3,4,5,1,2]s = [3, 4, 5, 1, 2]

This is a left rotation of the original array by 22 positions, confirming that Option A is correct.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions