✅✅ Java (0ms) || Easy to Understand || Begineer Friendly || Beats 100% users ✅✅
\n# Intuition\nThe problem requires rotating an array to the right by k steps. Initially, the intuition might be to perform the rotation directly by shifting el
\n# Intuition\nThe problem requires rotating an array to the right by k steps. Initially, the intuition might be to perform the rotation directly by shifting elements, but this approach would result in O(n * k) time complexity. Instead, a more efficient approach using array reversal can be employed.\n\n# Approach\n1. Take the modulo of k with the length of the array to handle cases where k is greater than the length of the array.\n2. Reverse the entire array to bring the last k elements to the beginning.\n3. Reverse the first k elements to move them to the end of the array.\n4. Reverse the remaining elements to restore the original order.\n\n# Complexity\n- Time complexity: O(n), where n is the number of elements in the array. The algorithm performs three array reversal operations, each taking linear time.\n- Space complexity: O(1), as the algorithm uses only a constant amount of extra space for variables regardless of the size of the input array.\n\n\nimage.png\n![image.png](https://assets.leetcode.com/users/images/11a2e6f9-a7b1-4851-ad34-0c562894283b_1711269702.7659798.png)\n\n# Code\n```\nclass Solution {\n    public void rotate(int[] nums, int k) {\n        k = k%nums.length;\n        // reverse complete arrya\n        reverseArray(nums, 0, nums.length-1);\n        // reverse left part of array excluding kth element\n        reverseArray(nums, 0, k-1);\n        // reverse right part of array starting with kth element\n        reverseArray(nums, k, nums.length-1);\n        \n    }\n\n    public void reverseArray(int[] a, int l, int r){\n        while(l <= r){\n            int t = a[l];\n            a[l] = a[r];\n            a[r] = t;\n            l++; r--;\n        }\n    }\n}\n```
['Array', 'Two Pointers', 'Java']