ISRO 2018 · Arrays & Matrix Representation

MCQ · 1 mark · Problem PROG-DSTR-0114

An array A consists of n integers in locations A[0], A[1], ..., A[n-1]. It is required to shift the elements of the array cyclically to the left by k places, where \(1 \le k \le n-1\). An incomplete algorithm for doing this in linear time, without using another array, is given below. B1 to B5 are the blanks.
min = n; i = 0;
while (B1) {
    temp = A[i]; j = i;
    while (B2) {
        A[j] = B3;
        j = (j + k) mod n;
        if (j < min) then min = j;
    }
    A[(n + i - k) mod n] = B4;
    i = B5;
}
Complete the algorithm by choosing B1; B2; B3; B4; B5 in that order.
  1. A
    \(i \gt \min ; \quad j \ne (n+1) \bmod n ; \quad A[j+k] ; \quad \text{temp} ; \quad i+1\)
  2. B
    \(i \lt \min ; \quad j \ne (n+i) \bmod n ; \quad A[j+k] ; \quad \text{temp} ; \quad i+1\)
  3. C
    \(i \gt \min ; \quad j \ne (n+i+k) \bmod n ; \quad A[j+k] ; \quad \text{temp} ; \quad i+1\)
  4. D
    \(i \lt \min ; \quad j \ne (n+i-k) \bmod n ; \quad A[(j+k) \bmod n] ; \quad \text{temp} ; \quad i+1\)

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solutionThe algorithm moves elements along the cycles \(i \to i+k \to i+2k \to \cdots\) (mod n). A left shift by k means the new A[j] is the old A[(j+k) mod n].B1 \(= i \lt \min\): min is the smallest index reached so far by a cycle; once i reaches it, every index has been moved.B2 \(= j \ne (n+i-k) \bmod n\): the cycle from i ends at \((i-k) \bmod n\), the cell just before it returns to i.B3 \(= A[(j+k) \bmod n]\): the index must wrap round; \(A[j+k]\) runs past the end of the array.B4 = temp: the last cell of the cycle gets the saved old A[i].B5 \(= i+1\): start the next cycle.Options A and C stop at once (\(i \gt \min\) is false at the start, as \(0 \lt n\)); option B never enters the inner loop (\(j=i=(n+i) \bmod n\)) and does not wrap the index.Answer: D

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com