diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..c47ce1aa --- /dev/null +++ b/Problem1.py @@ -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] 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 diff --git a/Problem3.py b/Problem3.py new file mode 100644 index 00000000..38e232a0 --- /dev/null +++ b/Problem3.py @@ -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 + +