✅ 🔥 0 ms Runtime Beats 100% User confirm 🔥|| Step By Steps Solution ✅ ||  Beginner Friendly  ✅ |
\n\n\u2705  IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Intuition:\nThe problem requires rotating the array to the right by \( k \) step
![Screenshot 2024-11-18 at 8.10.09\u202FAM.png](https://assets.leetcode.com/users/images/eb102f36-08ab-4d8d-8040-2901b11b6bb9_1731897700.4129508.png)\n\n\u2705  IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Intuition:\nThe problem requires rotating the array to the right by \\( k \\) steps. This can be achieved efficiently by using array manipulation instead of performing \\( k \\) rotations iteratively.\n\n---\n\n### Approach:\n1. **Modulo Operation**: Since rotating \\( n \\) times brings the array back to its original state, \\( k \\) can be reduced to \\( k \\mod n \\).\n2. **Reverse Technique**:\n   - Reverse the entire array.\n   - Reverse the first \\( k \\) elements.\n   - Reverse the remaining \\( n-k \\) elements.\n3. The final array will be the desired rotated version.\n\n---\n\n### Complexity:\n- **Time Complexity**: \\( O(n) \\), where \\( n \\) is the length of the array, as we perform three passes over the array.\n- **Space Complexity**: \\( O(1) \\), as the rotation is performed in-place.\n\n---\n\n### C++ Code:\n```cpp\n#include<vector>\n#include<algorithm>\nusing namespace std;\nclass Solution{\npublic:\nvoid rotate(vector<int>&nums,int k){\nint n=nums.size();\nk%=n;\nreverse(nums.begin(),nums.end());\nreverse(nums.begin(),nums.begin()+k);\nreverse(nums.begin()+k,nums.end());\n}\n};\n\n```\n\n---\n\n### Java Code:\n```java\nimport java.util.*;\nclass Solution{\npublic void rotate(int[]nums,int k){\nint n=nums.length;\nk%=n;\nreverse(nums,0,n-1);\nreverse(nums,0,k-1);\nreverse(nums,k,n-1);\n}\nprivate void reverse(int[]nums,int start,int end){\nwhile(start<end){\nint temp=nums[start];\nnums[start]=nums[end];\nnums[end]=temp;\nstart++;\nend--;\n}\n}\n}\n\n```\n\n---\n\n### Python 3 Code:\n```python\nclass Solution:\n    def rotate(self, nums: List[int], k: int) -> None:\n        n = len(nums)\n        k %= n\n        nums.reverse()\n        nums[:k] = reversed(nums[:k])\n        nums[k:] = reversed(nums[k:])\n```\n\n---\n\n### Steps Explanation:\n1. Reverse the entire array:\n   - Example: \\( [1,2,3,4,5,6,7] \\) \u2192 \\( [7,6,5,4,3,2,1] \\)\n2. Reverse the first \\( k \\) elements:\n   - Example: \\( [7,6,5,4,3,2,1] \\) \u2192 \\( [5,6,7,4,3,2,1] \\)\n3. Reverse the last \\( n-k \\) elements:\n   - Example: \\( [5,6,7,4,3,2,1] \\) \u2192 \\( [5,6,7,1,2,3,4] \\)\n\n\n\n![image.png](https://assets.leetcode.com/users/images/aadba7ae-8831-4ad2-b100-513cc93cdca6_1731897781.3936844.png)\n
['Array', 'Math', 'C++', 'Java', 'Python3']