GATE / CS ARCHIVE

GATE CSE 1994 / QUESTION 7

In-place cyclic rotation

Algorithms · Correctness, Invariants & Design · Full GATE CSE 1994 paper

GATE 1994, Q7 Descriptive
Report issue

Correctness, Invariants & Design

Question 7, GATE 1994: A[0..n−1] contains n integers. Shift it cyclically left K places, 1≤K≤n−1, in linear time without another array. Fill the five blanks in this skeleton.
min:=n; i:=0;
while ___ do begin
  temp:=A[i]; j:=i;
  while ___ do begin
    A[j]:=___; j:=(j+K) mod n;
    if j<min then min:=j;
  end;
  A[(n+i-K) mod n]:=___;
  i:=___;
end;
Tap to enlarge
Answer & solution

Answer: In order: i<min; (j+K) mod n ≠ i; A[(j+K) mod n]; temp; i+1. (no official key was published)

1. The desired assignment is new A[j]=old A[(j+K) mod n]. Follow this permutation one cycle at a time.

2. Save the first value in temp, copy forward along the cycle, and stop before the next source would be the overwritten start. The last destination is (i−K) mod n, where temp belongs.

3. Let g=gcd(n,K). The first cycle contains precisely the indices divisible by g. Its smallest positive visited index is g, so min becomes g. For K in the given range the cycle has at least two positions.

4. The remaining starts 1,…,g−1 cover the other residue classes. No update makes min smaller than g. After these g cycles the outer loop ends. Each index is assigned once, so time is Θ(n), with O(1) extra storage.

Code

min := n; i := 0
while i < min:
    temp = A[i]; j = i
    while (j + K) % n != i:
        A[j] = A[(j + K) % n]
        j = (j + K) % n
        if j < min: min = j
    A[(n + i - K) % n] = temp
    i = i + 1

Original paper, page 5