Skip to content
Merged
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
27 changes: 27 additions & 0 deletions PeakIndex.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//https://leetcode.com/problems/peak-index-in-a-mountain-array/

class Solution {
public int peakIndexInMountainArray(int[] arr) {
int start = 0;
int end = arr.length - 1;

while(start < end) {
int mid = start + (end - start) / 2;
if(arr[mid] > arr[mid+1]) {
// you are in dec part of the array
// this may be the ans, but look at left
end = mid;
} else {
// arr[mid + 1] > arr[mid]
// you are in inc part of the array
start = mid + 1;
}
}

// In the end, start == end and pointing to the largest number because of the 2 checks
// start and end are always trying to find max element in the above 2 checks
// hence, when they are pointing to just one element, that is the max element
// At every point of time of start and end, there may be a best possible ans at that particular time
return end;
}
}
31 changes: 31 additions & 0 deletions RotatedBinarySearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
public class RBS {
public static void main(String[] args) {


}

static int search(int[] arr, int target, int s, int e) {
if(s > e) {
return -1;
}

int m = s + (e-s) / 2;
if(arr[m] == target) {
return m;
}

if(arr[s] <= arr[m]) {
if(target >= arr[s] && target <= arr[m]) {
return search(arr, target, s, m-1);
} else {
return search(arr, target, m+1, e);
}
}

if(target >= arr[m] && target <= arr[e]) {
return search(arr, target, m+1, e);
}

return search(arr, target, s, m-1);
}
}