# 189 Rotate Array

Rotate an array ofnelements to the right byksteps.

For example, withn= 7 andk= 3, the array`[1,2,3,4,5,6,7]`is rotated to`[5,6,7,1,2,3,4]`.

**Note:**\
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

**Solution 1 (Extra Space, O(n)):** Hash to the location in the array the corresponds with its its rotated position.

```cpp
void rotate(vector<int>& nums, int k) 
{
    vector<int> r_nums(nums.size());

    for (int i = 0; i < nums.size(); i++) {
        int rotate_hash = (i + k) % nums.size();
        r_nums[rotate_hash] = nums[i];
    }
    nums = r_nums;
}

int main()
{
    vector<int> nums = { 1,2,3,4,5,6,7 };
    rotate(nums, 3);

    print(nums);
}
```

**Solution 2 (Constant Space, O(n)):** Reverse the array entirely, and the reverse two segments divided at k.

```
Example:

Input
nums: 1 2 3 4 5 6 7
k   : 3

rev :         7 6 5 4 3 2 1
rev(0, k) :   5 6 7 4 3 2 1
rev(k, end) : 5 6 7 1 2 3 4
```

```cpp
void rotate(vector<int>& nums, int k)
{
    k = k % nums.size();

    reverse(nums.begin(), nums.end());
    reverse(nums.begin(), nums.begin() + k);
    reverse(nums.begin() + k, nums.end());
}

int main()
{
    vector<int> nums = { 1,2,3,4,5,6,7 };
    rotate(nums, 3);
    print(nums);
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/189-rotate-array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
