Find the Rotation Count in Rotated Sorted array in JavaScript
Last Updated :
29 Aug, 2024
A 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 four 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.
Approach 1: Using Recursive Approach
In this approach, we will develop the recursive function that will give us the Rotation count. When we call the recursive function, it basically will check the middle element is the minimum element. If not, then it will search for the left and right parts of the array and then it will find the desired rotation count.
Syntax:
function functionName(parameters) {
// Base case: The condition where the recursion ends.
if (baseCaseCondition) {
// Return the base case value.
return baseCaseValue;
} else {
// Recursive call: Call the function with updated parameters.
return functionName(updatedParameters);
}
}
Example: In this example, we will find the rotation count in a rotated sorted array using the Recursive Approach.
JavaScript
function findRotationCount(arr_input, low_part, high_part) {
if (low_part >= high_part)
return 0;
if (arr_input[low_part] <= arr_input[high_part])
return low_part;
let mid_part =
Math.floor((low_part + high_part) / 2);
if (arr_input[mid_part] < arr_input[mid_part - 1]
&& arr_input[mid_part] < arr_input[mid_part + 1])
return mid_part;
if (arr_input[high_part] > arr_input[mid_part])
return findRotationCount(
arr_input, low_part, mid_part - 1);
else
return findRotationCount(
arr_input, mid_part + 1, high_part);
}
let inputArray = [4, 5, 6, 7, 1, 2, 3];
let output =
findRotationCount(
inputArray, 0, inputArray.length - 1);
console.log("Rotation Count is:", output);
OutputRotation Count is: 4
Approach 2: Using Modulo Operation Approach
In this approach, basically, we will use the modulo operation on the input-rotated array with respect to the 1st element of our array. The index where our modulo operation output becomes less will represent the rotation count.
Syntax:
a%b
Example: In this example, we will find the rotation count in a rotated sorted array using the Modulo Operation.
JavaScript
function rotationCountUsingModuloOperation(arrInput) {
let tempVar = arrInput.length;
let minimumIndex = 0;
let minimumValue = arrInput[0];
for (let i = 1; i < tempVar; i++) {
if (arrInput[i] < minimumValue) {
minimumValue = arrInput[i];
minimumIndex = i;
}
}
var rotationCountValue = minimumIndex % tempVar;
return rotationCountValue;
}
let inputArr = [6, 7, 8, 1, 2, 3, 4, 5]
let output = rotationCountUsingModuloOperation(inputArr);
console.log("Rotation Count is:", output);
OutputRotation Count is: 3
Approach 3: Using Repeated Concatenation and Substring
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);
OutputRotation Count is: 2
Approach 4: Two-Pointer Approach
- Initialize Pointers: Use two pointers to traverse the array.
- Find Rotation Point: Move through the array to find the point where the array order breaks (i.e., the smallest element).
- Count Rotations: The index of this smallest element is the rotation count.
Steps:
- Initialize Pointers:
start
pointer at the beginning of the array.end
pointer at the end of the array.
- Traverse the Array:
- Compare elements at
start
and end
. - Move the
start
or end
pointer to narrow down the search range based on the condition where the rotation point (smallest element) is found.
- Return the Rotation Count:
- The index where the smallest element is located gives the rotation count.
Example:
JavaScript
function findRotationCount(arr) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
if (arr[start] <= arr[end]) {
return start;
}
let mid = Math.floor((start + end) / 2);
let next = (mid + 1) % arr.length;
let prev = (mid + arr.length - 1) % arr.length;
if (arr[mid] <= arr[next] && arr[mid] <= arr[prev]) {
return mid;
}
// Decide the side to search
if (arr[mid] >= arr[start]) {
// The rotation point is in the right half
start = mid + 1;
} else {
// The rotation point is in the left half
end = mid - 1;
}
}
return 0;
}
const rotatedArray = [4, 5, 6, 7, 1, 2, 3];
const rotationCount = findRotationCount(rotatedArray);
console.log("Rotation count:", rotationCount);
Similar Reads
Javascript Program For Counting Rotations In Sorted And Rotated Linked List Given a linked list of n nodes which is first sorted, then rotated by k elements. Find the value of k.The idea is to traverse singly linked list to check condition whether current node value is greater than value of next node. If the given condition is true, then break the loop. Otherwise increase t
3 min read
Javascript Program to Count of rotations required to generate a sorted array Given an array arr[], the task is to find the number of rotations required to convert the given array to sorted form.Examples: Input: arr[] = {4, 5, 1, 2, 3}Â Output: 2Â Explanation:Â Sorted array {1, 2, 3, 4, 5} after 2 anti-clockwise rotations. Input: arr[] = {2, 1, 2, 2, 2}Â Output: 1Â Explanation:Â So
4 min read
Javascript Program to Count rotations required to sort given array in non-increasing order Given an array arr[] consisting of N integers, the task is to sort the array in non-increasing order by minimum number of anti-clockwise rotations. If it is not possible to sort the array, then print "-1". Otherwise, print the count of rotations. Examples: Input: arr[] = {2, 1, 5, 4, 3}Output: 2Expl
3 min read
How to Find Max Sum (i*arr[i]) with Array Rotations in JavaScript? Given an array where rotation operations are allowed, the task is to rotate the array any number of times and find the maximum possible sum of i*arr[i]. Examples : Input: arr = [1, 20, 2, 10] Output: 72 Explanation: We can get 72 by rotating array twice. [2, 10, 1, 20] 20*3 + 1*2 + 10*1 + 2*0 = 72 I
4 min read
Javascript Program to Count Inversions of size three in a given array Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3.Example : Input: {8, 4, 2, 1}Output: 4The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).Input: {9
4 min read
Javascript Program for Check if an array is sorted and rotated Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above ar
3 min read
Javascript Program to Count rotations divisible by 8 Given a large positive number as string, count all rotations of the given number which are divisible by 8.Examples: Input: 8Output: 1Input: 40Output: 1Rotation: 40 is divisible by 8 04 is not divisible by 8Input : 13502Output : 0No rotation is divisible by 8Input : 43262488612Output : 4Approach: It
3 min read
Javascript Program to Count rotations divisible by 4 Given a large positive number as string, count all rotations of the given number which are divisible by 4. Examples: Input: 8Output: 1Input: 20Output: 1Rotation: 20 is divisible by 4 02 is not divisible by 4Input : 13502Output : 0No rotation is divisible by 4Input : 43292816Output : 55 rotations are
2 min read
Javascript Program to Count 1's in a sorted binary array Given a binary array sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = {1, 1, 0, 0, 0, 0, 0} Output: 2 Input: arr[] = {1, 1, 1, 1, 1, 1, 1} Output: 7 Input: arr[] = {0, 0, 0, 0, 0, 0, 0} Output: 0A simple solution is to traverse the array linearly. The time comp
3 min read
Javascript Program to Count rotations which are divisible by 10 Given a number N, the task is to count all the rotations of the given number which are divisible by 10.Examples: Input: N = 10203 Output: 2 Explanation: There are 5 rotations possible for the given number. They are: 02031, 20310, 03102, 31020, 10203 Out of these rotations, only 20310 and 31020 are d
2 min read