1
+ /*
2
+
3
+ Suppose an array of length n sorted in ascending order is rotated between 1 and n times.
4
+ For example, the array nums = [0,1,2,4,5,6,7] might become:
5
+
6
+ [4,5,6,7,0,1,2] if it was rotated 4 times.
7
+ [0,1,2,4,5,6,7] if it was rotated 7 times.
8
+ Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
9
+
10
+ Given the sorted rotated array nums of unique elements, return the minimum element of this array.
11
+
12
+ You must write an algorithm that runs in O(log n) time.
13
+
14
+ Input: nums = [3,4,5,1,2]
15
+ Output: 1
16
+ Explanation: The original array was [1,2,3,4,5] rotated 3 times.
17
+
18
+ Constraints:
19
+ n == nums.length
20
+ 1 <= n <= 5000
21
+ -5000 <= nums[i] <= 5000
22
+ All the integers of nums are unique.
23
+ nums is sorted and rotated between 1 and n times.
24
+
25
+ */
26
+
27
+ /*
28
+ Time Complexity: O(log(N)), where N is the size of the array
29
+ Space Complexity: O(1), Constant Space
30
+ */
31
+
32
+ #include < bits/stdc++.h>
33
+ using namespace std ;
34
+
35
+ int findMin (vector<int > &nums)
36
+ {
37
+
38
+ int l = 0 ; // lower bound
39
+ int u = nums.size () - 1 ; // upper bound
40
+ int m = (l + u) / 2 ; // variable to track middle value
41
+ int n = nums.size ();
42
+ while (l <= u)
43
+ {
44
+ int next = (m + 1 ) % n; // to track next index of middle value
45
+ int prev = (m - 1 + n) % n; // to track previoys index of middle value
46
+ if (nums[l] <= nums[u]) // if array is sorted => return value present at lower bound
47
+ return nums[l];
48
+ else if (nums[m] < nums[prev] && nums[m] < nums[next]) // if value at middle is less than value at next, previous => return value present at middle
49
+ return nums[m];
50
+ else if (nums[m] > nums[l]) // if value at middle > value at lower bound => update lower bound
51
+ l = next;
52
+ else if (nums[m] < nums[u]) // if value at middle < value at upper bound => update upper bound
53
+ u = prev;
54
+ else if (nums[u] <= nums[l]) // if value at upper <= value at lower bound => Whole array is reversed i.e. return value at upper bound
55
+ return nums[u];
56
+
57
+ m = (l + u) / 2 ;
58
+ }
59
+ return -1 ;
60
+ }
61
+
62
+ int main () // driver function
63
+ {
64
+ vector<int > array = {3 , 4 , 5 , 1 , 2 };
65
+ int ans = findMin (array);
66
+ cout << ans;
67
+ return 0 ;
68
+ }
0 commit comments