From 6d59826768fcb2d95445af3a32e15d7bd6fc5281 Mon Sep 17 00:00:00 2001 From: tejashree surve Date: Fri, 7 Oct 2022 18:38:19 +0530 Subject: [PATCH] Binary Search Problem solved of Leetcode --- .../BinarySearch/CheckIfNAndDoubleExist.java | 39 +++++++++ leetcode/BinarySearch/FindInMountain.java | 79 +++++++++++++++++++ leetcode/BinarySearch/FindPeakElement.java | 21 +++++ .../FirstAndTheLastPositionOfElement.java | 45 +++++++++++ leetcode/BinarySearch/FirstBadVersion.java | 30 +++++++ .../GuessNumberHigherOrLower.java | 31 ++++++++ .../LargetOrGreaterletterThenTarget.java | 19 +++++ .../BinarySearch/PeakIndexInMountain.java | 20 +++++ .../BinarySearch/SearchInsertPosition.java | 32 ++++++++ .../SerachInRotatedSortedArray.java | 61 ++++++++++++++ .../BinarySearch/SplitArrayLargestSum.java | 52 ++++++++++++ leetcode/BinarySearch/Sqrt.java | 25 ++++++ leetcode/BinarySearch/ValidPerfectSqure.java | 20 +++++ 13 files changed, 474 insertions(+) create mode 100644 leetcode/BinarySearch/CheckIfNAndDoubleExist.java create mode 100644 leetcode/BinarySearch/FindInMountain.java create mode 100644 leetcode/BinarySearch/FindPeakElement.java create mode 100644 leetcode/BinarySearch/FirstAndTheLastPositionOfElement.java create mode 100644 leetcode/BinarySearch/FirstBadVersion.java create mode 100644 leetcode/BinarySearch/GuessNumberHigherOrLower.java create mode 100644 leetcode/BinarySearch/LargetOrGreaterletterThenTarget.java create mode 100644 leetcode/BinarySearch/PeakIndexInMountain.java create mode 100644 leetcode/BinarySearch/SearchInsertPosition.java create mode 100644 leetcode/BinarySearch/SerachInRotatedSortedArray.java create mode 100644 leetcode/BinarySearch/SplitArrayLargestSum.java create mode 100644 leetcode/BinarySearch/Sqrt.java create mode 100644 leetcode/BinarySearch/ValidPerfectSqure.java diff --git a/leetcode/BinarySearch/CheckIfNAndDoubleExist.java b/leetcode/BinarySearch/CheckIfNAndDoubleExist.java new file mode 100644 index 0000000..65c83b7 --- /dev/null +++ b/leetcode/BinarySearch/CheckIfNAndDoubleExist.java @@ -0,0 +1,39 @@ +package leetcode.BinarySearch; + +public class CheckIfNAndDoubleExist { + + public static boolean checkIfExist(int[] arr) { + // if the arr size is two then we will check if the arr[0] is 2*arr1 + // of arr0/2 == arr1 the true else false + if(arr.length == 2){ + if(arr[0] == 2*arr[1] || arr[0]/2 == arr[1]){ + return true; + } + return false; + } + // here we will check for every value and pass to binery search array + for(int i = 0;i < arr.length;i++){ + if(binarySearch(arr,(2*arr[i]),i)){ + return true; + } + if(arr[i] % 2 == 0 && binarySearch(arr,(arr[i]/2),i)){ + return true; + } + } + return false; + } + public static boolean binarySearch(int[] arr,int target,int i){ + int start = i+1; + int end = arr.length-1; + while(start <= end){ + int mid = start +(end - start)/2; + if(arr[mid] == target || arr[start] == target || arr[end] == target){ + return true; + }else { + start = start + 1; + end = end - 1; + } + } + return false; + } +} diff --git a/leetcode/BinarySearch/FindInMountain.java b/leetcode/BinarySearch/FindInMountain.java new file mode 100644 index 0000000..26998b1 --- /dev/null +++ b/leetcode/BinarySearch/FindInMountain.java @@ -0,0 +1,79 @@ +package leetcode.BinarySearch; + +//here they have provided the interface which contain the get() index and length +// and catch is it should not call the get() function more then 100 times + +/** + * // This is MountainArray's API interface. + * // You should not implement it, or speculate about its implementation + * interface MountainArray { + * public int get(int index) {} + * public int length() {} + * } + */ + +public class FindInMountain { + + public int findInMountainArray(int target, MountainArray mountainArr) { + // find the peakValue which ic pivot value + // the array me contain duplicate + int peakIndex = peakValue(mountainArr); + + // and check if the value present in left first as this is not sorted array + + int leftSide = binarySearch(mountainArr, target, 0, peakIndex); + + // if value is present in left then return + if(leftSide != -1){ + return leftSide; + }else{ + // else check if the value is present in right array + return binarySearch(mountainArr, target, peakIndex+1, mountainArr.length()-1); + } + }; + public static int binarySearch (MountainArray array, int target,int startIndex,int endIndex){ + boolean isAscen = array.get(startIndex) < array.get(endIndex); + + while(startIndex <= endIndex){ + int midIndex = (startIndex + endIndex) / 2 ; + + int midValue = array.get(midIndex); + if (midValue == target){ + return midIndex; + } + + if(isAscen){ + if(midValue < target){ + startIndex = midIndex + 1; + } + if(midValue > target){ + endIndex = midIndex - 1; + } + }else{ + if(midValue > target){ + startIndex = midIndex + 1; + } + if(midValue < target){ + endIndex = midIndex - 1; + } + } + + } + return -1; + }; + + public static int peakValue(MountainArray array){ + int start = 0; + int mid = 0; + int end = array.length()-1; + while(start != end){ + mid = start + (end - start)/2; + if(array.get(mid+1) > array.get(mid)){ + start = mid + 1; + }else{ + end = mid; + } + } + return start; + }; +} diff --git a/leetcode/BinarySearch/FindPeakElement.java b/leetcode/BinarySearch/FindPeakElement.java new file mode 100644 index 0000000..fb63f84 --- /dev/null +++ b/leetcode/BinarySearch/FindPeakElement.java @@ -0,0 +1,21 @@ +package leetcode.BinarySearch; + +public class FindPeakElement { + // this is similar to finding pivot + public int findPeakElement(int[] nums) { + int start = 0; + int mid = 0; + int end = nums.length-1; + while(start != end){ + mid = start + (end - start)/2; + if(nums[mid+1] > nums[mid]){ + start = mid + 1; + }else{ + end = mid; + } + } + // the loop will exist when start == end so we can pass any value start or end + return start; + } +} + diff --git a/leetcode/BinarySearch/FirstAndTheLastPositionOfElement.java b/leetcode/BinarySearch/FirstAndTheLastPositionOfElement.java new file mode 100644 index 0000000..90c5ce2 --- /dev/null +++ b/leetcode/BinarySearch/FirstAndTheLastPositionOfElement.java @@ -0,0 +1,45 @@ +package leetcode.BinarySearch; + +class FirstAndTheLastPositionOfElement{ +public int[] searchRange(int[] nums, int target) { + int[] ans = {-1,-1}; + // we will be dividing the searching in two parts as starting searching from + // starting index or start searching form the end part + int startIndex = binarySearch(nums,target,true); + int endIndex = binarySearch(nums,target,false); + ans[0] = startIndex; + ans[1] = endIndex; + return ans; + } + + + public int binarySearch(int[] nums, int target,boolean isSearchingFromStart){ + int ans = -1; + int start = 0; + int end = nums.length - 1; + // search in simple binary search + while(start <= end){ + int mid = start + (end - start)/2; + // if mid element is greater then target then search in left side by change + // the position of end + if(nums[mid] > target){ + end = mid - 1; + // if mid is less the target then search in right by changing the position + // of the start index + }else if(nums[mid] < target){ + start = mid + 1; + }else{ + // if we found target the search for the start point on left and end point + // form the right + ans = mid; + if(isSearchingFromStart){ + end = mid - 1; + }else{ + start = mid+1; + } + } + } + return ans; + + } +} \ No newline at end of file diff --git a/leetcode/BinarySearch/FirstBadVersion.java b/leetcode/BinarySearch/FirstBadVersion.java new file mode 100644 index 0000000..6e8d093 --- /dev/null +++ b/leetcode/BinarySearch/FirstBadVersion.java @@ -0,0 +1,30 @@ +package leetcode.BinarySearch; + +/* The isBadVersion API is defined in the parent class VersionControl. + boolean isBadVersion(int version); */ + +public class FirstBadVersion { + public int firstBadVersion(int n) { + int start = 1; + int end = n; + int ans = 0; + // here they have provided the funtion of badVersion which will return the + // if the version is true or false + if(isBadVersion(start)){ + return start; + } + while(start <= end){ + int mid = start +(end - start)/2; + if(isBadVersion(mid)){ + // where the mide version is bad means we can save the ans + //and try to check finding the first bad version by changing the + // end index position + ans = mid; + end = mid - 1; + }else{ + start = mid + 1; + } + } + return ans; + } +} diff --git a/leetcode/BinarySearch/GuessNumberHigherOrLower.java b/leetcode/BinarySearch/GuessNumberHigherOrLower.java new file mode 100644 index 0000000..31a8715 --- /dev/null +++ b/leetcode/BinarySearch/GuessNumberHigherOrLower.java @@ -0,0 +1,31 @@ +package leetcode.BinarySearch; + +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * int guess(int num); + */ + + // they have provided the Interface which has method guess will return if the number provided + // is higher or lower or equal +public class GuessNumberHigherOrLower { + public int guessNumber(int n) { + int start = 0; + int end = n; + while(start <= end){ + int mid = start + (end - start)/2; + if(guess(mid) == 1){ + start = mid + 1; + }else if(guess(mid) == -1){ + end = mid - 1; + }else{ + return mid; + } + } + return -1; + } + +} diff --git a/leetcode/BinarySearch/LargetOrGreaterletterThenTarget.java b/leetcode/BinarySearch/LargetOrGreaterletterThenTarget.java new file mode 100644 index 0000000..bd95ba8 --- /dev/null +++ b/leetcode/BinarySearch/LargetOrGreaterletterThenTarget.java @@ -0,0 +1,19 @@ +package leetcode.BinarySearch; + +public class LargetOrGreaterletterThenTarget { + // similar to binary search ["c","f","j"] finding greater letter + + public char nextGreatestLetter(char[] letters, char target) { + int start = 0; + int end = letters.length - 1; + while(start <= end){ + int mid = start + (end - start)/2; + if(letters[mid] > target){ + end = mid - 1; + }else{ + start = mid + 1; + } + } + return letters[start % letters.length]; + } +} diff --git a/leetcode/BinarySearch/PeakIndexInMountain.java b/leetcode/BinarySearch/PeakIndexInMountain.java new file mode 100644 index 0000000..3da3d49 --- /dev/null +++ b/leetcode/BinarySearch/PeakIndexInMountain.java @@ -0,0 +1,20 @@ +package leetcode.BinarySearch; + + +public class PeakIndexInMountain{ + // similar as finding pivot + 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]){ + end = mid; + }else{ + start = mid + 1; + } + } + return start; + } + +} \ No newline at end of file diff --git a/leetcode/BinarySearch/SearchInsertPosition.java b/leetcode/BinarySearch/SearchInsertPosition.java new file mode 100644 index 0000000..0103a08 --- /dev/null +++ b/leetcode/BinarySearch/SearchInsertPosition.java @@ -0,0 +1,32 @@ +package leetcode.BinarySearch; + +public class SearchInsertPosition { + // this is similer solution as floor of the giving target number + // floor means - get the greater smallest value form the given target + // where we have to find the index of value which is greater smallest of the target value + // if the target is not present in the array + public int searchInsert(int[] nums, int target) { + int start = 0; + int end = nums.length-1; + // if the target is greater then the last value of the array which mean the position + // of the give target will the length of the array. + if(target > nums[end]){ + return nums.length; + } + while(start <= end){ + int mid = start + (end - start)/2; + if(nums[mid] < target){ + start = mid + 1; + }else if(nums[mid] > target){ + end = mid - 1; + }else{ + return mid; + } + } + // if we don't found the target then we will return the start index becuase the + // while loop will exit when the the target is not and start cross the end value + // where start will pointing the greater smallest value of target value; + return start; + + } +} diff --git a/leetcode/BinarySearch/SerachInRotatedSortedArray.java b/leetcode/BinarySearch/SerachInRotatedSortedArray.java new file mode 100644 index 0000000..3454738 --- /dev/null +++ b/leetcode/BinarySearch/SerachInRotatedSortedArray.java @@ -0,0 +1,61 @@ +package leetcode.BinarySearch; + +class SerachInRotatedSortedArray{ + public int search(int[] array, int target) { + // this will find the index point where the array is been rotated + int pivot = findPivot(array); + // if it return -1 means array is not rotated which means simple binary search + if(pivot == -1){ + return binarySearch(array, 0, array.length-1,target); + } + + // if the target is == to pivot(the gretest value) then return pivot + if(array[pivot] == target){ + return pivot; + } + + // if first value of array is less then target then we have to find the target + // on the left side of array as pivot will be the end point + if(array[0] <= target){ + return binarySearch(array, 0, pivot-1,target); + } + + // else target is greater then first then serach on right side of the array + // with pivot as the starting point + return binarySearch(array, pivot+1, array.length-1,target); + } + + public int findPivot(int[] array){ + int start = 0; + int end = array.length -1; + while(start <= end){ + int mid = start + (end - start)/2; + if(mid < end && array[mid] > array[mid+1]){ + return mid; + }else if(mid > start && array[mid] < array[mid - 1]){ + return mid - 1; + }else if(array[start] >= array[mid]){ + end = mid - 1; + }else if(array[start] <= array[mid]){ + start = mid + 1; + }else{ + return mid; + } + } + return -1; + } + + public int binarySearch(int[] array,int start,int end,int target){ + while(start <= end){ + int mid = start +(end - start)/2; + if(array[mid] < target){ + start = mid + 1; + }else if(array[mid] > target){ + end = mid - 1; + }else{ + return mid; + } + } + return -1; + } +} \ No newline at end of file diff --git a/leetcode/BinarySearch/SplitArrayLargestSum.java b/leetcode/BinarySearch/SplitArrayLargestSum.java new file mode 100644 index 0000000..cc6515a --- /dev/null +++ b/leetcode/BinarySearch/SplitArrayLargestSum.java @@ -0,0 +1,52 @@ +package leetcode.BinarySearch; + +public class SplitArrayLargestSum { + // here even if the array is not sorted does't mean we cannot use binary search + // we'v to find the minimized largest sum of the split which aries a question + // what will be the min value and larget value we can have afte spliting + // let say min value - split the array into n part(e.i the array.length part) + // which will give and single value of every values in array then the + // min value will be the larget value of the array + // max value - which we split the array in 1 array that is array it self then the + // max value will be the addition of all values in the array + // eg - [7,2,5,10,8] min - 10 & max - 32 then our answer will lies between [10,30] + // where we found the array which is sorted which mean apply binary search + public int splitArray(int[] array, int m) { + int end = 0; + int start = array[0]; + // we found min and max value of th array + for(int i : array){ + if(start <= i){ + start = i; + } + end = end + i; + } + // [10,32] we will apply the binary search + // let take mid and check if the value we need is the ans + while(start < end){ + int mid = start + (end -start)/2; + int piceses = 1; + int max = 0; + // here we split the array in pices as per mid value + for(int i : array){ + if(max + i > mid){ + max = i; + piceses++; + }else{ + max += i; + } + } + + // we check if the pices is less then the give m number if less then we will + // check the aproxx. ans in left else in right if the pices is equal then + // we will get the one condition where the start == end which is our ans + if(piceses > m){ + start = mid +1; + }else{ + end = mid; + } + + } + return end; + } +} diff --git a/leetcode/BinarySearch/Sqrt.java b/leetcode/BinarySearch/Sqrt.java new file mode 100644 index 0000000..42aaba6 --- /dev/null +++ b/leetcode/BinarySearch/Sqrt.java @@ -0,0 +1,25 @@ +package leetcode.BinarySearch; + +public class Sqrt { + // will be using binary serach + // always remember when ever you will see sorted array then try to apply binary + // search algo to find the ans + public int mySqrt(int num) { + long start = 0; + long end = num; + while (start <= end ){ + long mid = start + (end - start)/2; + // here we check if the mid* mid is squre root of the given number + //as we have use long because after multiplying the value it will exceed + // the capicity of the int + if(mid*mid < num){ + start = mid +1; + }else if(mid*mid > num){ + end = mid - 1 ; + }else{ + return (int)mid; + } + } + return (int)end; + } +} diff --git a/leetcode/BinarySearch/ValidPerfectSqure.java b/leetcode/BinarySearch/ValidPerfectSqure.java new file mode 100644 index 0000000..e612714 --- /dev/null +++ b/leetcode/BinarySearch/ValidPerfectSqure.java @@ -0,0 +1,20 @@ +package leetcode.BinarySearch; + +public class ValidPerfectSqure{ + // this is similar to sqrt problem just need to return true or false + public boolean isPerfectSquare(int num) { + long start = 1; + long end = num; + while(start <= end){ + long mid = start + (end - start)/2; + if(mid*mid < num){ + start = mid + 1; + }else if(mid*mid > num ){ + end = mid - 1; + }else{ + return true; + } + } + return false; + } +} \ No newline at end of file