diff --git a/FinaPeak.java b/FinaPeak.java new file mode 100644 index 00000000..60436e27 --- /dev/null +++ b/FinaPeak.java @@ -0,0 +1,40 @@ +// Time Complexity : O(logn) +// Space Complexity :O(1) +// Did this code successfully run on Leetcode :Yes +// Any problem you faced while coding this : +// I believe this algo works to move to highesr points as we are given both the end are -INFINITY +// that in turn mean going to the higher side will give you guranteed lower point->peak +// If the question is tweaked to have +INFINITY on both ends this algo of finding PEAK won't work, have to go for lienar + +//A tweak may be find trough where both ends are +INFINITY, same algo + +// Your code here along with comments explaining your approach in three sentences only +public class FinaPeak { + public int findPeakElement(int[] nums) { + int start = 0; + int end = nums.length -1; + while(start<=end) + { + int mid = start + (end-start)/2; + //check if mid is end nums[i] != nums[i + 1] and next -Infinity blindly return + //or for cases mid>0 + //if mid==0, bring mid to end as in the last cond + if(mid==end || (mid>0 && (nums[mid]>nums[mid-1] && nums[mid]>nums[mid+1]))) + { + return mid; + } + //nums[i] != nums[i + 1] for all valid i + //else can be same this algo won't work + else if(nums[mid]nums[mid+1]) + { + return nums[mid + 1]; + } + //reject the other half, + // if nums[mid] to nums[end] is sorted, pivot lies first half + else if(nums[mid]nums[end] ) + { + return new int[]{-1,-1}; + } + int firstIndex = findFirstIndex(nums,target,start,end); + int lastIndex = findLastIndex(nums,target,start,end); + return new int[]{firstIndex,lastIndex}; + } + + //Finds the first target element in sorted array + private int findFirstIndex(int[] nums,int target,int start,int end) + { + int index = -1; + while(start<=end) + { + int mid = start + (end-start)/2; + //can't move left further when mid is already start or mismatch + if(nums[mid]==target && (mid==start || nums[mid-1]!=nums[mid])) + { + index = mid; + break; + } + //can move left further + else if(nums[mid]==target) + { + end = mid -1; + } + //Same for finding element in sorted binary serach + else if(target