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
32 changes: 32 additions & 0 deletions ProblemOne.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
36 changes: 36 additions & 0 deletions ProblemThree.java
Original file line number Diff line number Diff line change
@@ -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;

}
}
34 changes: 34 additions & 0 deletions ProblemTwo.java
Original file line number Diff line number Diff line change
@@ -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;
}
}