« Rotate array

Problem

You have been given a random integer array/list(ARR) of size N. Write a function that rotates the given array/list by D elements(towards the left).

Note:

Change in the input array/list itself. You don't need to return or print the elements.

Input format :

The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.

First line of each test case or query contains an integer 'N' representing the size of the array/list.

Second line contains 'N' single space separated integers representing the elements in the array/list.

Third line contains the value of 'D' by which the array/list needs to be rotated.

Output Format :

For each test case, print the rotated array/list in a row separated by a single space.

Output for every test case will be printed in a separate line.

Constraints :

1 <= t <= 10^4

0 <= N <= 10^6

0 <= D <= N

Time Limit:

1 sec

Sample Input 1:

1

7

1 2 3 4 5 6 7

2

Sample Output 1:

3 4 5 6 7 1 2

Sample Input 2:

2

7

1 2 3 4 5 6 7

0

4

1 2 3 4

2

Sample Output 2:

1 2 3 4 5 6 7

3 4 1 2

Solution

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13
14void swap(int *input, int i, int j)
15{
16 int temp = input[i];
17 input[i] = input[j];
18 input[j] = temp;
19}
20
21void reverse(int *input, int start, int end)
22{
23 while (start < end)
24 {
25 swap(input, start, end);
26 start++;
27 end--;
28 }
29}
30
31void rotate(int *input, int d, int n)
32{
33 if (n == 0)
34 {
35 return;
36 }
37 d = d % n;
38 if (d == 0)
39 {
40 return;
41 }
42 reverse(input, 0, n - 1);
43 reverse(input, 0, n - d - 1);
44 reverse(input, n - d, n - 1);
45}
46
47int main()
48{
49 int t;
50 cin >> t;
51
52 while (t > 0)
53 {
54 int size;
55 cin >> size;
56
57 int *input = new int[size];
58
59 for (int i = 0; i < size; ++i)
60 {
61 cin >> input[i];
62 }
63
64 int d;
65 cin >> d;
66
67 rotate(input, d, size);
68
69 for (int i = 0; i < size; ++i)
70 {
71 cout << input[i] << " ";
72 }
73
74 delete[] input;
75 cout << endl;
76 t--;
77 }
78
79 return 0;
80}