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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read