Программа Javascript для поиска M-го элемента массива после K левых поворотов

Опубликовано: 20 Сентября, 2022

Даны неотрицательные целые числа K , M и массив arr[] с N элементами, найдите M элемент массива после K левых поворотов.

Примеры:

Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1
Output: 5
Explanation: 
The array after first left rotation a1[ ] = {4, 5, 23, 3}
The array after second left rotation a2[ ] = {5, 23, 3, 4}
st element after 2 left rotations is 5.

Input: arr[] = {1, 2, 3, 4, 5}, K = 3, M = 2
Output:
Explanation: 
The array after 3 left rotation has 5 at its second position.

Наивный подход: идея состоит в том, чтобы выполнить операцию поворота влево K раз, а затем найти M элемент конечного массива.

Временная сложность: O(N * K)
Вспомогательное пространство: O(N)

    Efficient Approach: To optimize the problem, observe the following points:

  1. If the array is rotated N times it returns the initial array again.

    For example, a[ ] = {1, 2, 3, 4, 5}, K=5 then the array after 5 left rotation a5[ ] = {1, 2, 3, 4, 5}.

    Therefore, the elements in the array after Kth rotation is the same as the element at index K%N in the original array.

  2. The Mth element of the array after K left rotations is

    { (K + M – 1) % N }th

    element in the original array.

  3.  
    Below is the implementation of the above approach:

    Javascript




    <script>
      
    // Javascript program for the above approach 
      
        // Function to return Mth element of
        // array after k left rotations
        function getFirstElement(a , N , K , M) {
      
            // The array comes to original state
            // after N rotations
            K %= N;
      
            // Mth element after k left rotations
            // is (K+M-1)%N th element of the
            // original array
            var index = (K + M - 1) % N;
      
            var result = a[index];
      
            // Return the result
            return result;
        }
      
        // Driver code
          
      
            // Array initialization
            var a = [ 3, 4, 5, 23 ];
      
            // Size of the array
            var N = a.length;
      
            // Given K rotation and Mth element
            // to be found after K rotation
            var K = 2, M = 1;
      
            // Function call
            document.write(getFirstElement(a, N, K, M));
      
    // This code contributed by gauravrajput1 
      
    </script>

    Output: 

    5

     

    Time complexity: O(1)
    Auxiliary Space: O(1)

    Please refer complete article on Find the Mth element of the Array after K left rotations for more details!