« Check Array rotation

Problem

You have been given an integer array/list(ARR) of size N. It has been sorted(in increasing order) and then rotated by some number 'K' in the right hand direction.

Your task is to write a function that returns the value of 'K', that means, the index from which the array/list has been rotated.

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.

Output Format :

For each test case, print the value of 'K' or the index from which which the array/list has been rotated.

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

Constraints :

1 <= t <= 10^2

0 <= N <= 10^5

Time Limit:

1 sec

Sample Input 1:

1

6

5 6 1 2 3 4

Sample Output 1:

2

Sample Input 2:

2

5

3 6 8 9 10

4

10 20 30 1

Sample Output 2:

0

3

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
14int arrayRotateCheck(int *input, int size)
15{
16 if (size == 0 || size == 1)
17 {
18 return 0;
19 }
20 if ((input[size - 1] > input[0]) && (input[0] <= input[1]))
21 {
22 return 0;
23 }
24 for (int i = 1; i < size; i++)
25 {
26 if (input[i] < input[i - 1] && input[i] <= input[(i + 1) % size])
27 {
28 return i;
29 }
30 }
31 return 0;
32}
33
34int main()
35{
36 int t;
37 cin >> t;
38 while (t > 0)
39 {
40
41 int size;
42 cin >> size;
43 int *input = new int[size];
44
45 for (int i = 0; i < size; i++)
46 {
47 cin >> input[i];
48 }
49
50 cout << arrayRotateCheck(input, size) << endl;
51 delete[] input;
52 t--;
53 }
54
55 return 0;
56}