Left Rotate an Array in Java - The Coding Shala

Home >> Java Programs >> Left Rotate an Array

 In this post, we will learn how to left rotate the elements of an array using the Java program.

Left Rotate an Array in Java

Write a Java program to left rotate an array by 1.

Example: 

Input: [1, 2, 3, 4, 5]
Output: [2, 3, 4, 5, 1]

Solution 1

We need to rotate the elements to left by 1 position. We can store the first element in one variable and using for loop will shift all the elements to left by 1 position.

syntax: arr[i] = arr[i+1]

After shifting all the elements move the first element[stored in variable] to the last index.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

import java.util.*;

public class Main {

    public static int[] leftRotate(int[] arr) {
        // first element will become last
        int first = arr[0];
        for (int i = 0; i < arr.length-1; i++) {
            // shift the elements to left
            arr[i] = arr[i+1];
        }
        arr[arr.length-1] = first;
        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println("Array before rotation: ");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }

        System.out.println("\nArray after left rotation by 1: ");
        arr = leftRotate(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output: 

Array before rotation: 
1 2 3 4 5 
Array after left rotation by 1: 
2 3 4 5 1 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala