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 BinarySearchInfiniteSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Time complexity: O(log N) - reducing the elements by half in each iteration
// Space complexity: O(1) - no extra space used
// Did this code successfully run on Leetcode : Will run it later with premium
// Any problem you faced while coding this : No
class BinarySearchInfiniteSortedArray {
public int search(ArrayReader reader, int target) {
int low = 0;
int high = 1;
while (reader.get(high) < target) {
// move the search to right of high
low = high + 1;
high *= 2;
} // breaks when the search range is found
// binary search for the target
while (low <= high) {
int mid = low + (high - low) / 2;
if (reader.get(mid) == target) {
// target found
return mid;
}
if (reader.get(mid) < target) {
// move the search to right of mid
low = mid + 1;
} else {
// move the search to left of mid
high = mid - 1;
}
}
// target not found
return -1;
}
}
40 changes: 40 additions & 0 deletions BinarySearchRotatedSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Time complexity: O(log N) - reducing the elements by half in each iteration
// Space complexity: O(1) - no extra space used
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
class BinarySearchRotatedSortedArray {
public int search(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // avoiding int overflow
if (nums[mid] == target) {
// target found
// return mid, which is its index
return mid;
}
// at least one half will be sorted
if (nums[low] <= nums[mid]) {
// left array is sorted
if (nums[low] <= target && target < nums[mid]) {
// target exists in the left sorted array
high = mid - 1;
} else {
// move to the right half of the array
low = mid + 1;
}
} else {
// right array is sorted
if (nums[mid] < target && target <= nums[high]) {
// target exists in the right sorted array
low = mid + 1;
} else {
// move to the left half of the array
high = mid - 1;
}
}
}
// target not found
return -1;
}
}