Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solved Problem 1, 2 and 3 #2001

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
30 changes: 30 additions & 0 deletions Problem-1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'''
Time Complexity: O(logn)
Space Complexity: O(1)
Ran successfully on leetcode
Difficulty: Was able to understand, but took some time to build the final logic
'''

class Solution:
def search(self, nums: List[int], target: int) -> int:
low, high = 0, len(nums) - 1

while low <= high:
mid = (low + high) // 2

if target == nums[mid]:
return mid

if nums[low] <= nums[mid]:
if target > nums[mid] or target < nums[low]:
low = mid + 1
else:
high = mid - 1
else:
if target < nums[mid] or target > nums[high]:
high = mid - 1
else:
low = mid + 1

return -1

28 changes: 28 additions & 0 deletions Problem-2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'''
Time Complexity: O(logn)
Space Complexity: O(1)
Ran successfully on leetcode
Difficulty: Solved quickly by implementing simple Binary search and handling the out of bounds situation,
updated the code by using binary search for getting the range as well
'''

class Solution:
def search(self, reader: 'ArrayReader', target: int) -> int:
low, high = 0, 1

while reader.get(high) < target:
low = high
high = 2*high

while low <= high:
mid = (low + high) // 2
midValue = reader.get(mid)

if target == midValue:
return mid
elif target < midValue:
high = mid - 1
else:
low = mid + 1

return -1
27 changes: 27 additions & 0 deletions Problem-3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'''
Time Complexity: O(log(mxn))
Space Complexity: O(1)
Ran successfully on leetcode
Difficulty: Used the mlogn solution before but updated it to log(mn) solution
'''
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(matrix[0])
low, high = 0, m*n - 1


while low <= high:
mid = low + (high - low)//2

r = mid // n
c = mid % n

if matrix[r][c] == target:
return True
elif matrix[r][c] < target:
low = mid + 1
else:
high = mid - 1

return False