AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumarraysrotation

~90s

Rotating an array left

The array A is 0-indexed. What are its contents at the end?

Integer A[0..4], i, t
Set A = {10, 20, 30, 40, 50}
Set t = A[0]
For i = 0 to 3
    Set A[i] = A[i + 1]
End For
Set A[4] = t
Print A
Show the answer and the worked solution

Correct answer: B.

20 30 40 50 10

Worked solution

  1. t saves A[0] = 10.
  2. The loop copies A[1] into A[0], A[2] into A[1], A[3] into A[2] and A[4] into A[3], giving 20 30 40 50 50.
  3. Set A[4] = t overwrites the duplicate with 10, giving 20 30 40 50 10.

Answer: 20 30 40 50 10.

The idea

A left rotation by one is a forward copy plus a wrap-around of the saved element. Copying in the other direction would destroy values before they are read, which is why the loop runs upwards here.

Shortcut. Check the ends: A[4] gets the saved first element, 10, and A[0] gets the old A[1], 20; only "20 30 40 50 10" has both.

Common trap. "50 10 20 30 40" is a rotation to the right, picked by misreading A[i] = A[i + 1] as moving each value one place right.

Rotating an array left — Pseudocode Aptitude Question

Rotating an array left: The array A is 0-indexed. What are its contents at the end? Answer and worked solution on CodeKairo.

Question

The array A is 0-indexed. What are its contents at the end?

Integer A[0..4], i, t
Set A = {10, 20, 30, 40, 50}
Set t = A[0]
For i = 0 to 3
    Set A[i] = A[i + 1]
End For
Set A[4] = t
Print A

Options

  1. 10 20 30 40 50
  2. 20 30 40 50 10
  3. 50 10 20 30 40
  4. 50 40 30 20 10
Show the answer and the worked solution

Correct answer: B. 20 30 40 50 10

Worked solution

  1. t saves A[0] = 10.
  2. The loop copies A[1] into A[0], A[2] into A[1], A[3] into A[2] and A[4] into A[3], giving 20 30 40 50 50.
  3. Set A[4] = t overwrites the duplicate with 10, giving 20 30 40 50 10.

Answer: 20 30 40 50 10.

The idea

A left rotation by one is a forward copy plus a wrap-around of the saved element. Copying in the other direction would destroy values before they are read, which is why the loop runs upwards here.

Shortcut. Check the ends: A[4] gets the saved first element, 10, and A[0] gets the old A[1], 20; only "20 30 40 50 10" has both.

Common trap. "50 10 20 30 40" is a rotation to the right, picked by misreading A[i] = A[i + 1] as moving each value one place right.

All Pseudocode questions · placement mock tests