Java
Array Manipulation
Element Shifting
Programming
Data Structures

Java, Shifting Elements in an Array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Shifting elements in a Java array means moving elements left or right by a number of positions. Java arrays are fixed-size, so shifting requires overwriting elements and handling the vacated positions. The standard approach uses System.arraycopy() for efficient bulk moves, or a manual loop for full control. For circular shifting (rotation), the three-reverse algorithm provides an O(n) in-place solution.

Left Shift by One Position

java
1int[] arr = {1, 2, 3, 4, 5};
2
3// Save the first element
4int first = arr[0];
5
6// Shift all elements one position to the left
7for (int i = 0; i < arr.length - 1; i++) {
8    arr[i] = arr[i + 1];
9}
10
11// Place the saved element at the end (rotation)
12arr[arr.length - 1] = first;
13
14// Result: [2, 3, 4, 5, 1]

Without saving and wrapping the first element, it is simply discarded and the last position is filled with a default or specified value.

Right Shift by One Position

java
1int[] arr = {1, 2, 3, 4, 5};
2
3int last = arr[arr.length - 1];
4
5// Shift all elements one position to the right
6for (int i = arr.length - 1; i > 0; i--) {
7    arr[i] = arr[i - 1];
8}
9
10arr[0] = last;
11
12// Result: [5, 1, 2, 3, 4]

The loop iterates backward to avoid overwriting values before they are moved.

Using System.arraycopy()

System.arraycopy() is a native method that copies array regions efficiently:

java
1int[] arr = {1, 2, 3, 4, 5};
2
3// Left shift by 1: copy arr[1..4] to arr[0..3]
4int first = arr[0];
5System.arraycopy(arr, 1, arr, 0, arr.length - 1);
6arr[arr.length - 1] = first;
7// Result: [2, 3, 4, 5, 1]
8
9// Right shift by 1: copy arr[0..3] to arr[1..4]
10int[] arr2 = {1, 2, 3, 4, 5};
11int last = arr2[arr2.length - 1];
12System.arraycopy(arr2, 0, arr2, 1, arr2.length - 1);
13arr2[0] = last;
14// Result: [5, 1, 2, 3, 4]

System.arraycopy(src, srcPos, dest, destPos, length) handles overlapping regions correctly when source and destination are the same array.

Shifting by K Positions

For shifting (rotating) by k positions, the three-reverse algorithm runs in O(n) time with O(1) space:

java
1public static void rotateLeft(int[] arr, int k) {
2    int n = arr.length;
3    k = k % n;  // Handle k > n
4    if (k == 0) return;
5
6    reverse(arr, 0, k - 1);
7    reverse(arr, k, n - 1);
8    reverse(arr, 0, n - 1);
9}
10
11public static void rotateRight(int[] arr, int k) {
12    int n = arr.length;
13    k = k % n;
14    if (k == 0) return;
15
16    reverse(arr, 0, n - 1);
17    reverse(arr, 0, k - 1);
18    reverse(arr, k, n - 1);
19}
20
21private static void reverse(int[] arr, int start, int end) {
22    while (start < end) {
23        int temp = arr[start];
24        arr[start] = arr[end];
25        arr[end] = temp;
26        start++;
27        end--;
28    }
29}
30
31// Usage
32int[] arr = {1, 2, 3, 4, 5};
33rotateLeft(arr, 2);
34// Result: [3, 4, 5, 1, 2]

Using a Temporary Array

A simpler but O(n) space approach copies elements to their new positions:

java
1public static int[] shiftLeft(int[] arr, int k) {
2    int n = arr.length;
3    k = k % n;
4    int[] result = new int[n];
5
6    for (int i = 0; i < n; i++) {
7        result[i] = arr[(i + k) % n];
8    }
9
10    return result;
11}
12
13int[] arr = {1, 2, 3, 4, 5};
14int[] shifted = shiftLeft(arr, 2);
15// shifted: [3, 4, 5, 1, 2]

Using Collections.rotate()

For List types, Java provides a built-in rotation method:

java
1import java.util.*;
2
3List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
4
5// Rotate right by 2 (positive = right)
6Collections.rotate(list, 2);
7// Result: [4, 5, 1, 2, 3]
8
9// Rotate left by 2 (negative = left)
10Collections.rotate(list, -2);
11// Result: [1, 2, 3, 4, 5]  (back to original)

Note that Collections.rotate() rotates right for positive values, which is the opposite convention of many manual implementations.

Shift Without Rotation (Fill with Default)

If you want to shift without wrapping elements around:

java
1int[] arr = {1, 2, 3, 4, 5};
2
3// Left shift by 2, fill with 0
4System.arraycopy(arr, 2, arr, 0, arr.length - 2);
5arr[arr.length - 2] = 0;
6arr[arr.length - 1] = 0;
7// Result: [3, 4, 5, 0, 0]
8
9// Right shift by 2, fill with 0
10int[] arr2 = {1, 2, 3, 4, 5};
11System.arraycopy(arr2, 0, arr2, 2, arr2.length - 2);
12arr2[0] = 0;
13arr2[1] = 0;
14// Result: [0, 0, 1, 2, 3]

Complexity Comparison

ApproachTimeSpaceIn-Place
Manual loop (shift by 1)O(n)O(1)Yes
System.arraycopy (shift by 1)O(n)O(1)Yes
Three-reverse (shift by k)O(n)O(1)Yes
Temporary array (shift by k)O(n)O(n)No
Collections.rotate (List)O(n)O(1)Yes

Common Pitfalls

  • Off-by-one errors in loop direction: When shifting right, iterate backward (i--). When shifting left, iterate forward (i++). Iterating in the wrong direction overwrites source elements before they are copied.
  • Forgetting k % n: If k is greater than the array length, you get ArrayIndexOutOfBoundsException. Always normalize k with k = k % arr.length first.
  • Empty array or k = 0: Both are edge cases that should return immediately. Dividing by zero (k % 0) crashes if you do not check arr.length == 0 before normalizing.
  • Confusing shift with rotation: A shift discards elements that fall off the edge and fills vacated positions with a default. A rotation wraps those elements to the other side. Make sure you implement the correct behavior.
  • System.arraycopy overlap: System.arraycopy handles overlapping source and destination correctly, but only when they are the same array. Copying between two different arrays with overlapping memory is undefined behavior in theory, though in practice Java arrays do not share memory.

Summary

  • Use a manual loop for single-position shifts with full control
  • Use System.arraycopy() for efficient bulk element moves
  • Use the three-reverse algorithm for O(n) time, O(1) space rotation by k positions
  • Use Collections.rotate() for List types (positive = right, negative = left)
  • Always normalize k with modulo and handle empty array edge cases

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.