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
29 changes: 29 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# SEARCH IN ROTATED SORTED ARRAY
# https://leetcode.com/problems/search-in-rotated-sorted-array/description/
class Solution(object):
def search(self, nums, target):
"""
Since its a partially rotated array half of array will be sorted out and we will have to do the comparisons and accordingly do binarys search
:type nums: List[int]
:type target: int
:rtype: int
"""
#initialize low and high boundary
low, high = 0, len(nums)-1
while (low<=high):
#get mid index
mid = (low + high)//2
if(nums[mid]==target):
return mid
##Left side sorted, check if target lies between low index and mid and accordingly update high index else update low index if target lies on right side
if(nums[low] <= nums[mid]):
if(nums[low]<=target < nums[mid]):
high = mid - 1
else:
low = mid + 1
else:
if(nums[mid]<target<=nums[high]):
low = mid + 1
else:
high = mid - 1
return -1
24 changes: 24 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#Search in a sorted array of unknown size
import ArrayReader

class Solution:
def search(self, reader: ArrayReader, target: int) -> int:
#Step 1 is to find the low and high boundaries
low, high = 0, 1
#Perform while the value at index high is less than target, initialize low to high
#multiply high by 2, the reason why we do that is for balance between time complexity
#and ensures we find time complexity of O(log n)
while(reader.get(high) < target):
low = high
high *= 2

while low <= high:
mid=(low + high)//2
value = reader.get(mid)
if(value==target):
return mid
elif value < target:
high = mid - 1
else:
low = mid + 1
return -1
27 changes: 27 additions & 0 deletions Problem3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# SEARCH 2D MATRIX
# https://leetcode.com/problems/search-a-2d-matrix/description/

class Solution(object):
def searchMatrix(self, matrix, target):
"""
Goal is consider the 2d matrix as a 1d array and then do binary search
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m, n = len(matrix), len(matrix[0])
low, high = 0, (m * n - 1)

while(low <= high):
mid = (low + high)//2
row = mid//n
col = mid % n
if(matrix[row][col] == target):
return True
elif(matrix[row][col] < target):
low = mid+1
else:
high = mid-1
return False