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
41 changes: 41 additions & 0 deletions SearchInRotatedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Time Complexity : O(log n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No


// Your code here along with comments explaining your approach in three sentences only
// 1: For a rotated sorted array, at least either left or right half of the array will be sorted
// 2: We use this property to determine which pointers to move to find the target
// 3: For a left sorted array, we move the high pointer closer, for a right sorted array, we move the low pointer closer
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;
}
if(nums[low] <= nums[mid]){
// left sorted
if(nums[low] <= target && nums[mid] > target){
high = mid - 1;
}
else{
low = mid + 1;
}
}
else{
// right sorted
if(nums[high] >= target && nums[mid] < target){
low = mid + 1;
}
else
high = mid - 1;
}
};
return -1;
}
}
35 changes: 35 additions & 0 deletions SearchInUnknownArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Time Complexity : O(log n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : No - premium question
// Any problem you faced while coding this : No


// Your code here along with comments explaining your approach in three sentences only
// 1: We set a fixed range to search within and then use ArrayReader to double the range in which we're searching
// 2: We use the ArrayReader to get the mid element
// 3: And use Binary Search as normal to find the target element
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;
};

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;
}
}