diff --git a/ProblemOne.java b/ProblemOne.java new file mode 100644 index 00000000..b1149d20 --- /dev/null +++ b/ProblemOne.java @@ -0,0 +1,32 @@ +//Ran on leetcode: Yes +//TC: O(log n*m) where n is number of rows and m is the number of cols +//SC: O(1) +//Imagine the 2D matrix as a 1D array and then apply binary search on it +class ProblemOne { + public boolean searchMatrix(int[][] matrix, int target) { + + int rowLen = matrix.length; + int colLen = matrix[0].length; + + int low = 0; + int high = (rowLen * colLen) - 1; + + //Binary search on the imaginary 1D array + while(low <= high){ + int mid = low + (high - low) / 2; + // Convert to the row and col index of the matrix to compare + int row = mid / colLen; + int col = mid % colLen; + if(matrix[row][col] == target){ + return true; + } + if(target < matrix[row][col]){ + high = mid - 1; + } else { + low = mid + 1; + } + } + + return false; + } +} \ No newline at end of file diff --git a/ProblemThree.java b/ProblemThree.java new file mode 100644 index 00000000..9f9c31bd --- /dev/null +++ b/ProblemThree.java @@ -0,0 +1,36 @@ +/** + * // This is ArrayReader's API interface. + * // You should not implement it, or speculate about its implementation + * interface ArrayReader { + * public int get(int index) {} + * } + */ +// Did this code successfully run on Leetcode : Yes + // TC: O(logn) + // SC: O(1) + // Use binary search since the array is sorted + // Start with array of size 2 and then increment by doubling size till we find if the target is in our range and then use binary search to find the element +class ProblemThree { + public int search(ArrayReader reader, int target) { + if(reader.get(0) == target){ + return 0; + } + + int low = 0; + int high = 1; + int mid; + while(low <= high){ + mid = low + (high - low) / 2; + if(reader.get(mid) == target) return mid; + if(target < reader.get(mid)){ + high = mid - 1; + } else { + high = high * 2; + low = mid + 1; + } + } + + return -1; + + } +} \ No newline at end of file diff --git a/ProblemTwo.java b/ProblemTwo.java new file mode 100644 index 00000000..d08c5c15 --- /dev/null +++ b/ProblemTwo.java @@ -0,0 +1,34 @@ +// Did this code successfully run on Leetcode : Yes +// TC: O(1) +// SC: O(1) +// Use binary search since it is a sorted array +// Check which half is sorted and then apply binary search on that half if the target is present in it or ignore it +class ProblemOne { + public int search(int[] nums, int target) { + int low = 0; + int high = nums.length - 1; + int mid; + + while(low <= high){ + mid = low + (high - low) / 2; + if(nums[mid] == target) return mid; + if(nums[low] <= nums[mid]){ + if(target >= nums[low] && target <= nums[mid]){ + high = mid - 1; + } + else { + low = mid + 1; + } + } else { + if(target >= nums[mid] && target <= nums[high]){ + low = mid + 1; + } + else { + high = mid -1; + } + } + } + + return -1; + } +} \ No newline at end of file