Open In App

JavaScript Program to Check if one Array is a Rotation of Another

JavaScript has various inbuilt methods using which one can check whether one array is simply a rotation of another given array. Below is the example given to understand the problem clearly

Example:

Input 
1 2 3 4 5
4 5 1 2 3

Output
True

There are different approaches to checking if one array is a rotation of another array which are described as follows:

Using concatenation

Concatenate the first array using concat method with itself to cover all possible rotations. Iterate through the concatenated array, extracting subarrays of the same length as the second array, starting from each index. Convert these subarrays and the second array to strings and compare them. If a match is found, return true else return false.

Example : To demonstrate check if one array is a rotation of another array using concatenation method

function isRotation(arr1, arr2) {
    if (arr1.length !== arr2.length) {
        return false;
    }
    const concatenated = arr1.concat(arr1);
    for (let i = 0; i < concatenated.length; i++) {
        if (concatenated
            .slice(i, i + arr2.length)
            .join() === arr2
                .join()) {
            return true;
        }
    }
    return false;
}


const array1 = [1, 2, 3, 4, 5];
const array2 = [4, 5, 1, 2, 3];
console.log(isRotation(array1, array2)); 

Output
true

Time complexity : O(n + mn)

Space complexity: O(n)

Using Join with include

If length of array are not equal , return false. We convert both arrays to strings using join() method and check if one is a substring of the other array concatenated with itself. If it is, return true, indicating that arr2 is a rotation of arr1. Otherwise it return false.

Example : To demonstrate checking if one array is a rotation of another array using join along with include.

function ArraysRotations(arr1, arr2) {
    if (arr1.length !== arr2.length) {
        return false;
    }

    let str1 = arr1
        .join('');
    let str2 = arr2
        .join('');

    return (str1 + str1)
        .includes(str2);
}

const array1 = [1, 2, 3, 4, 5];
const array2 = [4, 5, 1, 2, 3];
console.log(ArraysRotations(array1, array2)); 

Output
true

Time complexity: O(n + m + m * n)

Space complexity: O(n + m)

Article Tags :