forked from SauravP97/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch-in-rotated-sorted-array.py
More file actions
35 lines (28 loc) · 927 Bytes
/
search-in-rotated-sorted-array.py
File metadata and controls
35 lines (28 loc) · 927 Bytes
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
"""
Time Complexity: O(logn)
Space Complexity: O(1)
Point to observe: Each time either the left half will be sorted or the right half.
Hence Binary Search is a good option.
"""
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
low = 0
high = n-1
while low<=high:
mid = (low+high)//2
if nums[mid]==target:
return mid
# if left half is sorted
if nums[low]<=nums[mid]:
if nums[low]<=target<nums[mid]:
high = mid-1
else:
low = mid+1
# if right half is sorted
else:
if nums[mid]<target<=nums[high]:
low = mid+1
else:
high = mid-1
return -1