Skip to content

Commit f5ccb3a

Browse files
committed
added Search in Rotated Sorted Array (medium)
1 parent d859d80 commit f5ccb3a

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
# Search in Rotated Sorted Array
3+
[Leetcode Link](https://leetcode.com/problems/search-in-rotated-sorted-array/)
4+
5+
## Problem:
6+
7+
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
8+
9+
(i.e., `[0,1,2,4,5,6,7]` might become `[4,5,6,7,0,1,2]`).
10+
11+
You are given a target value to search. If found in the array return its index, otherwise return `-1`.
12+
13+
You may assume no duplicate exists in the array.
14+
15+
Your algorithm's runtime complexity must be in the order of *O(log n)*.
16+
17+
## Example:
18+
19+
```
20+
Input: nums = [4,5,6,7,0,1,2], target = 0
21+
Output: 4
22+
```
23+
```
24+
Input: nums = [4,5,6,7,0,1,2], target = 3
25+
Output: -1
26+
```
27+
28+
## Note:
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from typing import List
2+
3+
def search(nums: List[int], target: int) -> int:
4+
start = 0
5+
end = len(nums)-1
6+
while end >= start:
7+
mid = (start + end) // 2
8+
if target == nums[mid]:
9+
return mid
10+
if nums[mid] >= nums[start]:
11+
# mid belongs to left sorted subarray
12+
if target < nums[mid] and target >= nums[start]:
13+
# target is in left subarray
14+
end = mid - 1
15+
elif target < nums[mid] and target < nums[start]:
16+
# target is in right subarray
17+
start = mid + 1
18+
elif target > nums[mid]:
19+
# target is in right subarray
20+
start = mid + 1
21+
else:
22+
# mid belongs to right sorted subarray
23+
if target < nums[mid]:
24+
# target is in left subarray
25+
end = mid - 1
26+
elif target > nums[mid] and target <= nums[end]:
27+
# target is in right subarray
28+
start = mid + 1
29+
elif target > nums[mid] and target > nums[end]:
30+
# target is in left subarray
31+
end = mid - 1
32+
return -1
33+
34+
35+
36+
37+
# test driver
38+
nums = [4,5,6,7,0,1,2]
39+
target = 0
40+
print("Input: nums =", nums, ", target =", target)
41+
print("Output:", search(nums, target))
42+
print()
43+
44+
nums = [6,7,0,1,2,4,5]
45+
target = 0
46+
print("Input: nums =", nums, ", target =", target)
47+
print("Output:", search(nums, target))
48+
print()

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ Languages used: Java and Python
3939
- [Diagonal Traverse II](Medium/DiagonalTraverse2)
4040
- [Total Hamming Distance](Medium/TotalHammingDistance)
4141
- [Partition Array into Disjoint Intervals](Medium/PartitionArrayIntoDisjointIntervals)
42+
- [Search in Rotated Sorted Array](Medium/SearchInRotatedSortedArray)
4243
- Hard
4344

4445
---

0 commit comments

Comments
 (0)