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
43 changes: 43 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#Find First and Last Position of Element in Sorted Array
# Time complexity O(logn)

class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
#1st using binary array search for the starting index

left = 0
right = len(nums) - 1
leftIndex = -1
rightIndex = -1
while left <= right:
mid = left + (right-left)//2
if target == nums[mid]:
if mid == left or target != nums[mid-1]:
leftIndex = mid
break
if target > nums[mid]:
left = mid+1
else:
right = mid - 1


# if leftindex does not get updated, menas target is not present return [-1,-1]
if leftIndex == -1:
return [leftIndex, rightIndex]
#then using the binary search starting from the left index, the mid can point either to same or bigger number
left = leftIndex
right = len(nums) - 1
while left <= right:
mid = left + (right-left)//2

# if mid is pointing to same number move the left index ahead
if target == nums[mid]:
if mid==right or nums[mid+1] != target:
rightIndex = mid
break
left = mid+1
else:
right = mid - 1


return [leftIndex, rightIndex]
27 changes: 27 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#Find Minimum in Rotated Sorted Array

class Solution:
def findMin(self, nums: List[int]) -> int:
# in case of rotated array the lowest will always lie in unsorted part
# in case both parts are sorted then the smallest item will be on the left most element

left = 0
right = len(nums) - 1

while left <= right:
mid = left + (right-left)//2
#if both side elemnts of the mid are bigger means the mid is lowest point
#in case of boundary elements if the other isde is bigger than also it is smallest

val = nums[mid]
if (mid == 0 or val < nums[mid-1]) and (mid == len(nums)-1 or val < nums[mid+1]):
return val

if nums[right] > nums[mid]:
#right subarray is sorted, min will lie in left subarray
right = mid-1
else:
left = mid+1

# return anything as the code won't reach here
return -1
22 changes: 22 additions & 0 deletions Problem3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#Find Peak Element

class Solution:
def findPeakElement(self, nums: List[int]) -> int:
left = 0
right = len(nums) - 1

while left <= right:
mid = left + (right-left)//2
val = nums[mid]
# if peak return index
if (mid==0 or val > nums[mid-1]) and (mid == len(nums)-1 or val > nums[mid+1]):
return mid

# else move towards a peak by moving towards increasing number
if mid > 0 and nums[mid-1]>val:
right = mid-1
else:
left = mid+1

# return anything as the code won't reach here
return -1