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 SearchInRotatedArray
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Time Complexity : O(logn)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes

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;
} else if(nums[low] <= nums[mid]) { //if left side is sorted
//check if the target is present in left side
if(nums[low] <= target && nums[mid] > target) {
high = mid-1;
} else {
low = mid+1;
}

} else { // if right side is sorted
//check if the target is present in the right side
if(nums[mid] < target && nums[high] >= target) {
low = mid+1;
} else {
high = mid-1;
}
}
}
return -1;
}
}
30 changes: 30 additions & 0 deletions SearchInSortedArrayOfUnknownSize
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* // 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;
while(reader.get(high) < target) {
low = high;
high = 2*high; // we don't know the end of the stream , so considering high as double of low
}
//once we find the range and apply the binary search and keep move the high and low pointers.
while(low <= high) {
int mid = low + (high - low) / 2;
if(reader.get(mid) == target) {
return mid;
} else if(reader.get(mid) < target) {
low = mid+1;
} else {
high = mid-1;
}
}
return -1;
}
}
28 changes: 28 additions & 0 deletions Searcha2DMatrix
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0) {
return false;
}

int m = matrix.length;
int n = matrix[0].length;
//imagine of having 1d erray
int low = 0;
int high = m*n-1;

while(low <= high) {
int mid = low+(high-low)/2;
int r = mid/n; // find out the row index
int c = mid%n; // find out the column index
//apply binary search and check if the target resides in corresponding matrix row.
if(matrix[r][c] == target) {
return true;
} else if(matrix[r][c] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return false;
}
}