✅ 🔥 Super Easy 3-Step Array Rotation! 🚀 (Beats 100% 🔥) [Video Solution 📺]
IntuitionThe problem requires rotating an array to the right by k steps. Instead of shifting elements one by one (which is inefficient), we can use the 3-step r
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires rotating an array to the right by k steps. Instead of shifting elements one by one (which is inefficient), we can use the 3-step reversal algorithm to achieve the rotation in-place efficiently.

# Solution Video:
[https://youtu.be/2uXtgUom5T8]()

🔔 Subscribe for more coding solutions! 👉 [Click Here](https://www.youtube.com/@How_to_Code?sub_confirmation=1)
# Approach
<!-- Describe your approach to solving the problem. -->
Reverse the entire array to bring the last k elements to the front (but in reverse order).
Reverse the first k elements to restore their correct order.
Reverse the remaining n-k elements to place them correctly.
This effectively shifts elements in O(n) time with O(1) space.

# Explanation:
Example:
📌 Input: nums = [1,2,3,4,5,6,7], k = 3

1️⃣ Reverse the entire array:
Before: [1, 2, 3, 4, 5, 6, 7]
After: [7, 6, 5, 4, 3, 2, 1]

2️⃣ Reverse the first k elements (k = 3):
Before: [7, 6, 5, 4, 3, 2, 1]
After: [5, 6, 7, 4, 3, 2, 1]

3️⃣ Reverse the remaining n-k elements (n-k = 4):
Before: [5, 6, 7, 4, 3, 2, 1]
After: [5, 6, 7, 1, 2, 3, 4] ✅ (Correctly rotated)

# Complexity
- Time complexity: O(n) (Each reversal operation runs in O(n))
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: O(1) (In-place modification, no extra space used)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->


# Code
```cpp []
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
    int n = nums.size();
    k = k % n; // Handle cases where k >= n

    // Step 1: Reverse the entire array
    reverse(nums.begin(), nums.end());

    // Step 2: Reverse the first k elements
    reverse(nums.begin(), nums.begin() + k);

    // Step 3: Reverse the remaining n-k elements
    reverse(nums.begin() + k, nums.end());
        
    }
};
```

# Call to Action:
✅ If you found this solution helpful, please upvote it! 👍 It motivates me to create more high-quality explanations. 🚀

🔔 Subscribe for more coding solutions! 👉 [Click Here](https://www.youtube.com/@How_to_Code?sub_confirmation=1)
['Array', 'Math', 'C++']