Rotate Array Left By K Positions

Write a function that rotates a list by k elements.

For example, [1, 2, 3, 4, 5, 6] rotated by two becomes [3, 4, 5, 6, 1, 2].

Example:

Input:  arr[]={1,2,3,4,5,6}, k =2
Output: [3,4,5,6,1,2]

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void reverseArray(vector<int&arrint lowint high)
{
    while (low < high)
    {
        swap(arr[low]arr[high]);
        low++;
        high--;
    }
}
void rotateArrayLeftByK(vector<int&arrint k)
{

    //reverse first k elements
    reverseArray(arr0k - 1);

    //reverse the last n-k elements
    reverseArray(arrkarr.size() - 1);

    //reverse the whole array
    reverseArray(arr0arr.size() - 1);
}
int main()
{
    vector<intarr = {123456};

    int k = 2;

    k = k % arr.size();
    rotateArrayLeftByK(arrk);
    cout << "[";
    for (int i = 0i < arr.size(); i++)
    {
        cout << arr[i];
        if (i != arr.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment