How to use concatenation In Javascript
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)
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:
Table of Content
- Using concatenation
- Using Join with include