diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..fbd37c75 --- /dev/null +++ b/Problem1.py @@ -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] \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..9d456855 --- /dev/null +++ b/Problem2.py @@ -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 \ No newline at end of file diff --git a/Problem3.py b/Problem3.py new file mode 100644 index 00000000..8736560e --- /dev/null +++ b/Problem3.py @@ -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 \ No newline at end of file