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
43 changes: 43 additions & 0 deletions LC33.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Time Complexity : O(logN)
// Space Complexity : O(1)


// Your code here along with comments explaining your approach
//Create pointers low and high and calculate mid
//check if the left side is sorted or the right side at this point.
//if the left side is sorted, check if the target value lies in that window. If not, move the low pointer to mid+1.
// same for the right side
// return the mid element if target is found
// else return -1 if while loop exits without finding the target value.

class Solution {
public int search(int[] nums, int target) {
//1
int low = 0;
int high = nums.length - 1;

//2
while(low <= high){
int mid = low + (high - low)/2;

//3
if(nums[mid] == target){
return mid;
} else if(nums[mid] >= nums[low]){
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;
}
}
}
//4
return -1;
}
}
42 changes: 42 additions & 0 deletions LC702.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Time Complexity : O(logN)
// Space Complexity : O(1)



// Your code here along with comments explaining your approach
//Create pointers low, high and calculate mid
//keep updating value of high until you get Integer.MAX_VALUE because that means you have hit array out of bound
//create a separate function specifically for binary search and use it to return the value in the search method.


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

while(reader.get(high) != Integer.MAX_VALUE){
high = high*2;
}

return binarySearch(reader, low, high, target);

}

private int binarySearch(ArrayReader reader, int low, int high, int target){
while(low <= high){
int mid = low + (high - low)/2;

if(reader.get(mid) == target){
return mid;
}
else if(reader.get(mid) > target){
high = mid - 1;
}
else{
low = mid + 1;
}

}
return -1;
}
}