DATA STRUCTURES PROGRAM • ARRAY TECHNIQUES

Rotate an Array with the Reversal Algorithm

Rotate an array left by two positions using three in-place reversals.

IntermediateReversal algorithmRotationIn-place

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
3 4 5 6 7 1 2

COMPLETE C PROGRAM

Complete C implementation

dsa-array-rotation-reversal.c
Open in compiler
#include <stdio.h>

void reverse(int values[], int left, int right)
{
    while (left < right) {
        int temporary = values[left];
        values[left++] = values[right];
        values[right--] = temporary;
    }
}

int main(void)
{
    int values[] = {1, 2, 3, 4, 5, 6, 7};
    int length = 7, positions = 2;
    reverse(values, 0, positions - 1);
    reverse(values, positions, length - 1);
    reverse(values, 0, length - 1);
    for (int index = 0; index < length; index++) printf("%d ", values[index]);
    putchar('\n');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

3 4 5 6 7 1 2
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Start with {1, 2, 3, 4, 5, 6, 7}; length is 7 and positions is 2.
  2. Reverse indices 0 through 1 to get {2, 1, 3, 4, 5, 6, 7}.
  3. Reverse indices 2 through 6 to get {2, 1, 7, 6, 5, 4, 3}.
  4. Reverse the whole array to get {3, 4, 5, 6, 7, 1, 2}, then print it.

Write the array as two segments A and B, where A contains the first k elements. Reversing A, then B, then the complete array transforms reverse(A) + reverse(B) into B + A. Each reversal swaps the two outer elements and moves the endpoints inward. The total work is O(n), and the temporary variable needs O(1) auxiliary space. The supplied example uses a fixed array and does not read input. Its indices are valid for 0 <= positions <= length. For a general API with length > 0, normalize a non-negative rotation count using positions %= length; handle an empty array before taking the remainder.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

This is a left rotation: do not expect the output of a right rotation.

Check this

Keep the first segment endpoint at positions - 1; using positions reverses one extra element.

Check this

Do not use positions greater than length with these calls: the first reversal can access outside the array.

Try it yourself

Practice: Set positions to 0 or 7: the output should stay 1 2 3 4 5 6 7. Set it to 1: expect 2 3 4 5 6 7 1. Before trying positions = 9, add normalization for the non-empty array; it should then behave like positions = 2.