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
69 changes: 69 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -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]


26 changes: 26 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -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