GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Arrays/search_rotated_sorted_array.py at master · onowdev/coding-problems

Expand file tree

/

search_rotated_sorted_array.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
69 lines (51 loc) · 1.57 KB
/

search_rotated_sorted_array.py

Copy path

File metadata and controls

69 lines (51 loc) · 1.57 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
'''
Search in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Input: [4, 5, 6, 7, 0, 1, 2], 0
Output: 4
Input: [4, 5, 6, 7, 0, 1, 2], 3
Output: -1
=========================================
Use binary search twice, first time to find the pivot (index where the array is rotated)
and the second time to find the target.
Time Complexity: O(LogN)
Space Complexity: O(1)
'''
############
# Solution #
############
def search_rotated_sorted_array(nums, target):
n = len(nums)
pivot = find_pivot(nums, 0, n) + 1
if pivot > n:
return -1
if nums[0] <= target:
return find_element(nums, 0, pivot - 1, target)
return find_element(nums, pivot, n - 1, target)
def find_pivot(nums, left, right):
while left < right - 1:
mid = left + (right - left) // 2
if nums[left] < nums[mid]:
left = mid
else:
right = mid
return left
def find_element(nums, left, right, target):
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
###########
# Testing #
###########
# Test 1
# Correct result => 4
print(search_rotated_sorted_array([4, 5, 6, 7, 0, 1, 2], 0))
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.