diff --git a/Find Minimum in Rotated Sorted Array.py b/Find Minimum in Rotated Sorted Array.py new file mode 100644 index 00000000..87009a4f --- /dev/null +++ b/Find Minimum in Rotated Sorted Array.py @@ -0,0 +1,32 @@ +# Check if the first elememt in the array < last elemet in the array. If it is, return the +# first element. Else, take the mid and see if array[mid-1]>array[mid]. if it is, return mid. Else, +# check which side of the array is sorted. If the left side is sorted, low = mid+1 else high = mid -1 + +# Time complexity: O(logn) +# Space complexity: O(1) + + +class Solution(object): + def findMin(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + low = 0 + high = len(nums)-1 + + while low<=high: + if nums[low]0 and nums[mid-1]>nums[mid]: + return nums[mid] + else: + if nums[low]<=nums[mid]: + low = mid+1 + else: + high=mid-1 + return nums[mid] + + + \ No newline at end of file diff --git a/Find Peak Element.py b/Find Peak Element.py new file mode 100644 index 00000000..f27c2384 --- /dev/null +++ b/Find Peak Element.py @@ -0,0 +1,32 @@ +# If there is only one element, return its index. If there are 2 elements, retuen the index of the +# grater one. Else, calcualte mid. Check if array[mid-1]array[mid+1] to see +# if its the peek element. If true, return mid. Else, check if array[mid+1]>array[mid], if yes, low = mid+1 +# else high=mid -1 + +# Time complexity: O(logn) +# Space complexity: O(1) + + +class Solution(object): + def findPeakElement(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n = len(nums) + if n==1: + return 0 + if n==2: + return 0 if nums[0]>nums[1] else 1 + + low=0 + high = n-1 + while low<=high: + mid = (low+high)//2 + if (mid==0 or nums[mid]>nums[mid-1]) and (mid==n-1 or nums[mid]>nums[mid+1] ): + return mid + elif midnums[mid+1]: + high=mid-1 + \ No newline at end of file diff --git a/First and last positioned Element in Sorted Array.py b/First and last positioned Element in Sorted Array.py new file mode 100644 index 00000000..63fdbec7 --- /dev/null +++ b/First and last positioned Element in Sorted Array.py @@ -0,0 +1,56 @@ +# For first index - Take mid, if array[mid] is equal to target, check if the element before it is leeser than the +# current element. If it is, then return mid. Else, high=mid-1. If the elememt < target, low =mid+1 +# else high=mid-1 +# For last index - Take mid, if array[mid] is equal to target, check if the element after it is grater than the +# current element. If it is, then return mid. Else, low=mid+1. If the elememt < target, low =mid+1 +# else high=mid-1 + +# Time complexity: O(logn) +# Space complexity: O(1) + +class Solution(object): + def searchRange(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + low = 0 + high = len(nums)-1 + first_ind=-1 + while low<=high: + mid = (low+high)//2 + if nums[mid] == target: + if mid == 0 or nums[mid-1]