Arrays Easy - Part II (Rotations)

Chetan DattaChetan Datta
2 min read

I. Left Rotate an Array by One

Problem Statement

Given an array of N integers, left rotate the array by one place. (link)

Optimal Approach

To perform a left rotation of the array by one element involves shifting each element to the left by one position.

Code

public class Solution {

    static int[] rotateArray(int[] a, int n) {

        int storeFirst = a[0];

        for(int i=1; i<n; i++){
            a[i-1] = a[i];
        }
        a[n-1] = storeFirst;
        return a;
    }
}

II. Rotate Array

Problem Statement

Given an array of integers, rotating array of elements by k elements either left or right. (link)

Optimal Solution

When rotation is encountered, our default strategy is to perform reversal. Whether it involves left or right rotation, the straightforward procedure is:

  1. Identify the partition point.

  2. Reverse each of the two blocks separately.

  3. Reverse the entire array.

Code - I (Using Collections)

    public static ArrayList<Integer> rotateArray(ArrayList<Integer> arr, int k) {
        int n = arr.size();
        k %= n;
        Collections.reverse(arr.subList(0, k));
        Collections.reverse(arr.subList(k, n));
        Collections.reverse(arr.subList(0, n));
        return arr;
    }

Code - II (Custom Reverse Functionality)


public class Solution {
    public static ArrayList<Integer> rotateArray(ArrayList<Integer> arr, int k) {
        int n = arr.size();
        k %= n;
        reverse(arr, 0, k);
        reverse(arr, k, n);
        reverse(arr, 0, n);
        return arr;
    }

    public static void reverse(List<Integer> arr, int first, int last){
        int size = (last+first);
        for(int i=first; i<(size>>1); i++){
            swap(arr, i, size-i-1);
        }
    }

    public static void swap(List<Integer> arr, int i, int j){
        int temp = arr.get(i);
        arr.set(i, arr.get(j));
        arr.set(j, temp);
    }
}
0
Subscribe to my newsletter

Read articles from Chetan Datta directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chetan Datta
Chetan Datta

I'm someone deeply engrossed in the world of software developement, and I find joy in sharing my thoughts and insights on various topics. You can explore my exclusive content here, where I meticulously document all things tech-related that spark my curiosity. Stay connected for my latest discoveries and observations.