Skip to content
Open

Done #2314

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
42 changes: 42 additions & 0 deletions FirstndLast.py
Original file line number Diff line number Diff line change
@@ -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]
23 changes: 23 additions & 0 deletions findMin.py
Original file line number Diff line number Diff line change
@@ -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
22 changes: 22 additions & 0 deletions findpeak.py
Original file line number Diff line number Diff line change
@@ -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