diff --git a/search_2D_matrix.java b/search_2D_matrix.java new file mode 100644 index 00000000..6b523283 --- /dev/null +++ b/search_2D_matrix.java @@ -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; + } +} diff --git a/search_in_infinte_sorted_array.java b/search_in_infinte_sorted_array.java new file mode 100644 index 00000000..614eb0bc --- /dev/null +++ b/search_in_infinte_sorted_array.java @@ -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; + } +} \ No newline at end of file diff --git a/search_in_rotated_sorted_array.java b/search_in_rotated_sorted_array.java new file mode 100644 index 00000000..e69de29b