forked from super30admin/Binary-Search-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminInRotatedArray.py
26 lines (21 loc) · 939 Bytes
/
minInRotatedArray.py
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
# Time Complexity = O(logn)
# Space Complexity = O(1)
class Solution:
def findMin(self, nums: list[int]) -> int:
if len(nums) == 1:
return nums[0]
low = 0
high = len(nums) - 1
while (low <= high):
# If the array is already sorted
if nums[low] <= nums[high]:
return nums[low]
mid = low + ((high - low) // 2)
# Checking if mid is the minima
if (mid == 0 or nums[mid] < nums[mid + 1]) and (mid == len(nums) - 1 or nums[mid] < nums[mid - 1]):
return nums[mid]
# Deciding the direction of traversal along array
elif nums[low] <= nums[mid]: # Left array is sorted, move rightwards
low = mid + 1
else: # Right array is sorted, move leftwards
high = mid - 1