How to useRepeated Concatenation and Substring in Javascript
In this approach first of all we will concatenate our inputted or the original array with itself. Then we will find the sorted substring that is equal to the original array length. After doing this, starting index of the sorted substring which is repeated will consists of the rotation count.
Syntax:
function rotationCountUsingConcat(arrInput) {
const dupArray =
arrInput.concat(arrInput);
const sortedSubstr =
dupArray.slice().sort((a, b) => a - b);
const rotCountVal =
dupArray.indexOf(sortedSubstr[0]);
return rotCountVal;
}
Example: In this example, the rotationCountUsingConcat function calculates the rotation count of a circularly rotated array using concatenation, sorting, and index finding.
Javascript
function rotationCountUsingConcat(arrInput) { const dupArray = arrInput.concat(arrInput); const sortedSubstr = dupArray.slice().sort((a, b) => a - b); const rotCountVal = dupArray.indexOf(sortedSubstr[0]); return rotCountVal; } const inputArr = [15, 18, 2, 3, 6, 12]; const output = rotationCountUsingConcat(inputArr); console.log( "Rotation Count is:" , output); |
Rotation Count is: 2
Find the Rotation Count in Rotated Sorted array in JavaScript
Rotated Sorted Array is an array type in JavaScript that has been rotated to the left or right by some random number of positions. In this article, we will understand how to find the count of rotations performed on the original sorted array to obtain the given sorted array using JavaScript language. In this article, we will mainly cover three different approaches.
There are different approaches for finding the rotation count in a rotated sorted array in JavaScript. Let’s discuss each of them one by one.
- Using Recursive Approach
- Using Modulo Operation Approach
- Repeated Concatenation and Substring Approach
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us