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
31 changes: 31 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Time Complexity : O(log(m*n)) where m is the number of rows and n is the number of columns in the matrix
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this :No

// Your code here along with comments explaining your approach
// We are treating the 2D matrix as a 1D array and applying binary search on it.
// We calculate the mid index and then find the corresponding row and column in the matrix using the mid index. We then compare the value at that position with the target and adjust our low and high pointers accordingly until we find the target or exhaust our search space.
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int total = m*n;
int low = 0;
int high = total-1;
while(low<=high){
int mid = low + (high-low/2);
int row = mid/n;
int column = mid%n;
if(matrix[row][column] == target){
return true;
}else if(matrix[row][column] < target){
low = mid+1;
}else{
high = mid-1;
}
}
return false;

}
}
43 changes: 43 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Time Complexity : O(log n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

// Your code here along with comments explaining your approach
// We are using binary search to find the target in the rotated sorted array.
// We calculate the mid index and then determine which side of the array is sorted.
// Based on the sorted side, we adjust our search range accordingly.
class Solution {
public int search(int[] nums, int target) {
int low = 0;
int high = nums.length-1;
while(low<=high){
int 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[high] && target >= nums[mid]){
low = mid +1;
}else{
high = mid -1;
}

}
//5,6,7,0,1,2,3



}

return -1;


}
}