Left Rotation - HackerRank | C++ Implementation


Problem:

A left rotation operation on an array of size n shifts each of the array’s elements 1 unit to the left. For example, if 2 left rotations are performed on array [1, 2, 3, 4, 5], then the array would become [3, 4, 5, 1, 2].

Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.

Read the full problem here : Left Rotation

Solution:

Left Rotation HackerRank

This is a very easy problem. In the above figure we see that after two rotations, the element at index 2 is the first element in the new array. Thus after d rotations, the element at index d is the first element. And all elements after dth elements with follow.

1
2
3
4
for (std::size_t i = rotations; i < arr.size(); ++i)
{
    rotated_array.push_back(arr[i]);
}

Now, elements from 0 to d-1 indices are added to the new rotated array.

1
2
3
4
for (std::size_t i = 0; i < rotations; ++i)
{
    rotated_array.push_back(arr[i]);
}


C++ Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <vector>

std::vector<int> left_rotation(std::vector<int>& arr, int rotations)
{
    std::vector<int> rotated_array;

    for (std::size_t i = rotations; i < arr.size(); ++i)
    {
        rotated_array.push_back(arr[i]);
    }
    for (std::size_t i = 0; i < rotations; ++i)
    {
        rotated_array.push_back(arr[i]);
    }
    return rotated_array;
}

int main()
{
    int num_elements, num_left_rotations;

    std::cin >> num_elements;
    std::cin >> num_left_rotations;

    std::vector<int> input_array(num_elements);
    for (int i = 0; i < num_elements; ++i)
    {
        std::cin >> input_array[i];
    }

    std::vector<int> result_array = left_rotation(input_array, num_left_rotations);

    for (int i = 0; i < num_elements; ++i)
    {
        std::cout << result_array[i] <<" ";
    }
    std::cout << "\n";
}

View this on Github

If you have another solution then please share it in the comments below.

Other Competitive Programming Problems and Solutions

Repeated String
Picking Numbers