From b8dde4c1d678ae4be4412b8624eddf9c2d945242 Mon Sep 17 00:00:00 2001 From: Divyam22 Date: Sat, 23 Aug 2025 21:09:56 -0400 Subject: [PATCH] Done with Binary-Search-2 --- Problem1.py | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++ Problem2.py | 26 ++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 Problem1.py create mode 100644 Problem2.py diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..5809b87b --- /dev/null +++ b/Problem1.py @@ -0,0 +1,69 @@ +""" +TC: O(log(N)) {since we perform binary search to first find the element, and then do two binary searches in each half to search for + the lowest and the highest. Since constants dont matter in time complexities, we get O(log(N)) t.c.} +SC: O(1) {we dont use any extra spaces} + +The problem succesfully ran on LeetCode +""" + +class Solution: + def searchRange(self, nums: List[int], target: int) -> List[int]: + if len(nums) == 0: + return [-1,-1] + if len(nums) == 1: + return [0,0] if nums[0] == target else [-1,-1] + + def expand(idx): + # for searching the lowest occurence + low = 0 + high = idx + + lowest = high + + while low <= high: + mid = low + (high - low)//2 + if nums[mid] == target: + high = mid - 1 + lowest = mid + elif nums[mid] < target: + low = mid + 1 + else: + break + + # searching for the highest + low = idx + high = len(nums)-1 + highest = low + + while low <= high: + mid = low + (high - low)//2 + if target == nums[mid]: + low = mid + 1 + highest = mid + elif target < nums[mid]: + high = mid - 1 + else: + break + return [lowest, highest] + + + + + + low, high = 0, len(nums) - 1 + + while low <= high: + mid = low + (high - low)//2 + + if target == nums[mid]: + start, end = expand(mid) + return [start, end] + + if nums[mid] < target: + low = mid + 1 + else: + high = mid - 1 + + return [-1, -1] + + \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..e71b6309 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,26 @@ +""" +TC: O(log(N)) {The minimum always lie in the unsorted half of the array, hence we discard the sorted half of the array + and continue our search on the other half, we get O(log(N)) t.c.} +SC: O(1) {we dont use any extra spaces} + +The problem succesfully ran on LeetCode +""" + +class Solution: + def findMin(self, nums: List[int]) -> int: + if len(nums) == 1: + return nums[0] + low, high = 0, len(nums)-1 + + while low<=high: + mid = low + (high-low)//2 + + if nums[low] <= nums[high]: + return nums[low] + + if nums[low] <= nums[mid]: + low = mid + 1 + else: + high = mid + +