JavaScript Program to Find Mth element after K Right Rotations of an Array


We are writing a JavaScript program to find the mth element after k right rotations of an array. Firstly, we will take the input for the array, m and k. Then, we will use a loop to perform the right rotations. In each iteration of the loop, we will move the last element of the array to the first position. We will continue this loop for k times to get the rotated array. Finally, we will return the mth element of the rotated array as the result.

Approach

The approach for finding the mth element after k right rotations of an array can be broken down as follows −

  • Calculate the actual position of the mth element after k rotations, which would be (m-k) % n, where n is the length of the array.

  • Check if the calculated position is negative, in which case it can be converted to a positive position by adding n to it.

  • Return the element at the calculated position in the array.

  • To optimize this solution, you can use the modulo operator to keep the calculated position within the bounds of the array, so you don't need to check for negative values.

  • The time complexity of this solution is O(1), as the calculation of the final position and the retrieval of the element at that position are both constant-time operations.

  • The space complexity is O(1), as no additional data structures are used in the solution.

Example

Here is an example of a JavaScript program that finds the mth element after k right rotations of an array

function findElement(arr, k, m) {
   k = k % arr.length; // handling large k values
   return arr[(arr.length - k + m - 1) % arr.length];
}
let arr = [1, 2, 3, 4, 5];
let k = 2;
let m = 3;
console.log(findElement(arr, k, m));

Explanation

  • The findElement function takes in an array arr, number of rotations k, and the mth element to find.

  • The k = k % arr.length line calculates the actual number of rotations performed on the array after handling large k values. This is done because rotating the array more than its length does not change its position, hence taking k modulo the length of the array gives the actual number of rotations performed.

  • The line return arr[(arr.length - k + m - 1) % arr.length]; calculates the position of the mth element after k rotations. The expression arr.length - k gives the starting position of the array after k rotations, and then + m - 1 gives the position of the mth element, and finally, taking the modulo with the length of the array ensures that the position wraps around the end of the array if it goes beyond the bounds.

  • Finally, the program calls the findElement function and logs the result. In this case, the output would be 4.

Updated on: 15-Mar-2023

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements