Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
l=0
r=len(nums)-1
flag=False
#Doing binary search to see if the target is present or not
while l<=r:
m=l+(r-l)//2
if nums[m]==target:
flag=True
break
elif nums[m]>target:
r=m-1
else:
l=m+1
if flag==False:
return [-1,-1]

# Doing binary search to find a target less than target
# we can do it in space[l,m]
left= l
right = m
while left<=right:
mid= left+ (right-left)//2
if nums[mid]<target:
left=mid+1
else:
right=mid-1
res1=left
# Do binary search to find a target greater than target
# we can do it in space[m,r]
left= m
right = r
while left<=right:
mid= left+ (right-left)//2
if nums[mid]<=target:
left=mid+1
else:
right=mid-1
res2=right
return [res1,res2]

16 changes: 16 additions & 0 deletions problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution:
def findMin(self, nums: List[int]) -> int:
l=0
r=len(nums)-1
while l<r:
m=l+(r-l)//2
# This implies mid can not be minimum as it is greater than something
if nums[m]>nums[r]:
l=m+1
# Here mid can be minimum so keeping r=m
else:
r=m
return nums[r]



17 changes: 17 additions & 0 deletions problem3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
l=0
r=len(nums)-1
while l<r:
m=l+(r-l)//2
#This implies there is a greater element to the right
# Since no two adjacent elements are equal as per the constraints
# If the elements further are greater/smaller we are guaranteed to find a peak as the boundaries are -infinity
if nums[m]<nums[m+1]:
l=m+1
else:
r=m
return l