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
24 changes: 24 additions & 0 deletions search_2D_matrix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
public class search_2D_matrix {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;

int low = 0;
int high = m * n - 1;

while (low <= high) {
int mid = low + (high-low)/2;
int r = mid / n;
int c = mid % n;

if (matrix[r][c] == target) {
return true;
} else if (matrix[r][c] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return false;
}
}
37 changes: 37 additions & 0 deletions search_in_infinte_sorted_array.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Time Complexity : O(log k), where k is the index of the target
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

/**
* // This is ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* interface ArrayReader {
* public int get(int index) {}
* }
*/

class Solution {
public int search(ArrayReader reader, int target) {
int low = 0;
int high = 1;

// First expand the search boundary exponentially until high is large enough to include the target.
// Then perform binary search within that range to find the target efficiently.
// This works well for unknown-sized sorted arrays because it avoids needing the array length.
while (reader.get(high) < target) {
low = high;
high = 2 * high;
}

while (low <= high) {
int mid = low + (high - low) / 2;
int value = reader.get(mid);

if (value == target) return mid;
if (value > target) high = mid - 1;
else low = mid + 1;
}
return -1;
}
}
Empty file.