diff --git a/FirstndLast.py b/FirstndLast.py new file mode 100644 index 00000000..58d9dc08 --- /dev/null +++ b/FirstndLast.py @@ -0,0 +1,42 @@ +# Time Complexity : O(log n) +# Space Complexity : O(1) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Use two binary searches. The first binary search finds the first occurrence and +# The second binary search finds the last occurrence + +class Solution: + def searchRange(self, nums: List[int], target: int) -> List[int]: + + def findFirst(l, h): + while l <= h: + m = (l + h) // 2 + if nums[m] == target: + if m == 0 or nums[m - 1] != target: + return m + h = m - 1 + elif nums[m] < target: + l = m + 1 + else: + h = m - 1 + return -1 + + def findSecond(l, h): + while l <= h: + m = (l + h) // 2 + if nums[m] == target: + if m == len(nums) - 1 or nums[m + 1] != target: + return m + l = m + 1 + elif nums[m] > target: + h = m - 1 + else: + l = m + 1 + return -1 + + first = findFirst(0, len(nums) - 1) + if first == -1: + return [-1, -1] + + second = findSecond(first, len(nums) - 1) + return [first, second] diff --git a/findMin.py b/findMin.py new file mode 100644 index 00000000..ce09befa --- /dev/null +++ b/findMin.py @@ -0,0 +1,23 @@ +# Time Complexity : O(log n) +# Space Complexity : O(1) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Use binary search on the rotated sorted array and +# Track the minimum value while narrowing the search space. + +class Solution: + def findMin(self, nums: List[int]) -> int: + l = 0 + h = len(nums) - 1 + res = float('inf') + + while l <= h: + m = (l + h) // 2 + res = min(res, nums[m]) + + if nums[m] > nums[h]: + l = m + 1 + else: + h = m - 1 + + return res diff --git a/findpeak.py b/findpeak.py new file mode 100644 index 00000000..6b05e5f7 --- /dev/null +++ b/findpeak.py @@ -0,0 +1,22 @@ +# Time Complexity : O(log n) +# Space Complexity : O(1) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: +# Use binary search to find a peak element. A peak element is greater than its neighbors. +# Narrow the search space until a peak is found. + +class Solution: + def findPeakElement(self, nums: List[int]) -> int: + l = 0 + h = len(nums) - 1 + while l <= h: + m = (l + h) // 2 + if (m == 0 or nums[m - 1] < nums[m]) and (m == len(nums) - 1 or nums[m] > nums[m + 1]): + return m + elif nums[m + 1] > nums[m]: + l = m + 1 + else: + h = m - 1 + + return -1