Skip to content

Commit 529f126

Browse files
committed
added leetcode array solutions in python
1 parent a0d8a31 commit 529f126

File tree

2 files changed

+109
-0
lines changed

2 files changed

+109
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class Solution(object):
2+
def searchRange(self, nums, target):
3+
"""
4+
:type nums: List[int]
5+
:type target: int
6+
:rtype: List[int]
7+
"""
8+
res= [-1]*2
9+
lo= 0
10+
n= len(nums)
11+
hi= n-1
12+
if (n==0):
13+
return res
14+
while (lo<hi):
15+
mid= lo + (hi-lo)//2
16+
if (nums[mid]>= target):
17+
hi= mid
18+
else:
19+
lo= mid+1
20+
21+
22+
if (nums[lo]!=target):
23+
return res
24+
res[0]= lo #found lower bound
25+
26+
27+
lo= 0
28+
hi= n-1
29+
30+
while (lo<hi):
31+
mid= lo +(hi-lo+1)//2
32+
33+
if (nums[mid]> target):
34+
hi= mid-1
35+
else:
36+
lo= mid
37+
38+
res[1]= lo#upper bound
39+
return res
40+
41+
42+
43+
"""
44+
Time complexity: O(log(n))
45+
Space complexity: O(1), constant space
46+
47+
Find more details of the framework used here: https://www.topcoder.com/community/competitive-programming/tutorials/binary-search/
48+
49+
"""
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Solution(object):
2+
@staticmethod
3+
def searchHelper(nums,lo,hi,target):
4+
while lo<=hi:
5+
mid= lo + (hi-lo)/2
6+
if nums[mid]==target:
7+
return mid
8+
elif nums[mid]>target:
9+
hi= mid-1
10+
else:
11+
lo= mid+1
12+
return -1
13+
14+
def search(self, nums, target):
15+
"""
16+
:type nums: List[int]
17+
:type target: int
18+
:rtype: int
19+
"""
20+
n= len(nums)
21+
lo= 0
22+
hi= n-1
23+
if n==0:
24+
return -1
25+
26+
while (lo<hi):
27+
mid= lo+ (hi-lo)/2
28+
if (nums[mid]<nums[0]):
29+
hi= mid
30+
else:
31+
lo= mid+1
32+
minm= lo
33+
#lo is the index of the minimum element
34+
35+
#now we have 2 sorted(ascending) subarrays, thus do a binary search on each of them
36+
37+
if (nums[lo]==target):
38+
return lo
39+
40+
else:
41+
#simple binary search on nums[0:lo-1]
42+
resIdx= Solution.searchHelper(nums, 0, minm-1, target)
43+
if (resIdx!=-1):
44+
return resIdx
45+
#not found in the first part
46+
resIdx= Solution.searchHelper(nums, minm, n-1, target)
47+
48+
#binary search on nums[lo+1,n-1] second part
49+
50+
51+
return resIdx#target not found anywhere
52+
53+
54+
'''
55+
Time complexity of the algorithm(asymptotically):
56+
O(log(n)), where n is the size of the input array
57+
Space complexity is constant, O(1)
58+
Find more details of the framework used here: https://www.topcoder.com/community/competitive-programming/tutorials/binary-search/
59+
60+
'''

0 commit comments

Comments
 (0)