-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathCheck array rotation.cpp
71 lines (54 loc) · 1.59 KB
/
Check array rotation.cpp
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
Check Array Rotation
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
*/
int arrayRotateCheck(int *arr, int size) {
//Write your code here
// we will use binary search to solve this question
int low = 0;
int high = size - 1;
while(low < high) {
int mid = low + ((high - low ) / 2);
if(arr[mid] < arr[0]) {
high = mid;
}
else if (arr[mid] >= arr[0]) {
low = mid + 1;
}
}
// sanity check
if(arr[low] < arr[0]){
return low;
} else {
return 0;
}
}
// Time Complexity : O(logn)
// Space Complexity : O(1)