diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..f9128470 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,18 @@ +{ + "configurations": [ + { + "name": "windows-gcc-x86", + "includePath": [ + "${workspaceFolder}/**" + ], + "compilerPath": "C:/MinGW/bin/gcc.exe", + "cStandard": "${default}", + "cppStandard": "${default}", + "intelliSenseMode": "windows-gcc-x86", + "compilerArgs": [ + "" + ] + } + ], + "version": 4 +} \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..611217c2 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,24 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "C/C++ Runner: Debug Session", + "type": "cppdbg", + "request": "launch", + "args": [], + "stopAtEntry": false, + "externalConsole": true, + "cwd": "c:/Users/HP/Data-Structures-and-Algorithms", + "program": "c:/Users/HP/Data-Structures-and-Algorithms/build/Debug/outDebug", + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ] + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..bb879da5 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,59 @@ +{ + "C_Cpp_Runner.cCompilerPath": "gcc", + "C_Cpp_Runner.cppCompilerPath": "g++", + "C_Cpp_Runner.debuggerPath": "gdb", + "C_Cpp_Runner.cStandard": "", + "C_Cpp_Runner.cppStandard": "", + "C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/VR_NR/Community/VC/Auxiliary/Build/vcvarsall.bat", + "C_Cpp_Runner.useMsvc": false, + "C_Cpp_Runner.warnings": [ + "-Wall", + "-Wextra", + "-Wpedantic", + "-Wshadow", + "-Wformat=2", + "-Wcast-align", + "-Wconversion", + "-Wsign-conversion", + "-Wnull-dereference" + ], + "C_Cpp_Runner.msvcWarnings": [ + "/W4", + "/permissive-", + "/w14242", + "/w14287", + "/w14296", + "/w14311", + "/w14826", + "/w44062", + "/w44242", + "/w14905", + "/w14906", + "/w14263", + "/w44265", + "/w14928" + ], + "C_Cpp_Runner.enableWarnings": true, + "C_Cpp_Runner.warningsAsError": false, + "C_Cpp_Runner.compilerArgs": [], + "C_Cpp_Runner.linkerArgs": [], + "C_Cpp_Runner.includePaths": [], + "C_Cpp_Runner.includeSearch": [ + "*", + "**/*" + ], + "C_Cpp_Runner.excludeSearch": [ + "**/build", + "**/build/**", + "**/.*", + "**/.*/**", + "**/.vscode", + "**/.vscode/**" + ], + "C_Cpp_Runner.useAddressSanitizer": false, + "C_Cpp_Runner.useUndefinedSanitizer": false, + "C_Cpp_Runner.useLeakSanitizer": false, + "C_Cpp_Runner.showCompilationTime": false, + "C_Cpp_Runner.useLinkTimeOptimization": false, + "C_Cpp_Runner.msvcSecureNoWarnings": false +} \ No newline at end of file diff --git a/Java/BinarySearch/BinarySearchOnAnswers/AggressiveCow.java b/Java/BinarySearch/BinarySearchOnAnswers/AggressiveCow.java new file mode 100644 index 00000000..889eb048 --- /dev/null +++ b/Java/BinarySearch/BinarySearchOnAnswers/AggressiveCow.java @@ -0,0 +1,43 @@ +public class AggressiveCow { + public static void main(String args[]) + { + int[] stalls={1,2,4,8,9}; + int cows=3; + int result=aggressiveCows(stalls,cows); + System.out.println("The largest minimum distance is : "+result); + } + public static int aggressiveCows(int[] stalls,int cows) + { + int left=1; + int right=stalls[stalls.length-1]-stalls[0]; + int answer=-1; + while(left<=right) + { + int mid=left+(right-left)/2; + if(canPlaceCows(stalls,cows,mid)) + { + answer=mid; + left=mid+1; + } + else{ + right=mid-1; + } + } + return answer; + } + public static boolean canPlaceCows(int[] stalls,int cows,int distance) + { + int countCows=1; + int lastPosition=stalls[0]; + for(int i=1;i=distance) + { + countCows++; + lastPosition=stalls[i]; + + } + } + return countCows>=cows; + } +} diff --git a/Java/BinarySearch/BinarySearchOnAnswers/ApproachOnBinarySearchOnAnswers.md b/Java/BinarySearch/BinarySearchOnAnswers/ApproachOnBinarySearchOnAnswers.md new file mode 100644 index 00000000..05f29206 --- /dev/null +++ b/Java/BinarySearch/BinarySearchOnAnswers/ApproachOnBinarySearchOnAnswers.md @@ -0,0 +1,157 @@ +

🌸 Minimum Number of Days to Make Bouquets

+ +

Problem Statement

+

+Untitled Diagram drawio +

+ +

You are given an integer array bloomDay[] where:

+ + + + +

Tasks

+
    +
  1. Return the minimum number of days required to make M bouquets
  2. +
  3. If it is not possible, return -1
  4. +
+ +
+ +

Key Observations

+ +

1️) Feasibility Check (Fail Fast)

+ +

To make M bouquets of K flowers each:

+ +
+Total flowers required = M × K
+
+ +

If:

+ +
+M × K > bloomDay.length
+
+ +

It is impossible to form the bouquets, so return -1.

+ +
+

+Untitled Diagram drawio (3) +

+ +

2️) Why Binary Search Works

+ +

This problem is not about searching indices.

+

It is about searchin

Define a function:

+ +
+CanMakeBouquet(day)
+
+ + + +

This creates a monotonic pattern:

+ +
+F F F F F T T T T
+
+ +

Perfect use case for Binary Search on Answer.

+ +
+ +

Approach

+ + + +
+ + +

Java Implementation

+ +
+
+
+class Solution {
+    public int minDays(int[] bloomDay, int m, int k) {
+
+        if ((long) m * k > bloomDay.length) return -1;
+
+        int low = Integer.MAX_VALUE, high = Integer.MIN_VALUE;
+        for (int day : bloomDay) {
+            low = Math.min(low, day);
+            high = Math.max(high, day);
+        }
+
+        int ans = -1;
+        while (low <= high) {
+            int mid = low + (high - low) / 2;
+
+            if (canMakeBouquet(bloomDay, m, k, mid)) {
+                ans = mid;
+                high = mid - 1;
+            } else {
+                low = mid + 1;
+            }
+        }
+        return ans;
+    }
+
+    private boolean canMakeBouquet(int[] bloomDay, int m, int k, int days) {
+        int count = 0;
+
+        for (int day : bloomDay) {
+            if (day <= days) {
+                count++;
+                if (count == k) {
+                    m--;
+                    count = 0;
+                }
+            } else {
+                count = 0;
+            }
+        }
+        return m <= 0;
+    }
+}
+
+
+
+ +
+ +

⏱ Complexity Analysis

+ + + +
+ +

+Binary Search is not only for sorted arrays.
+It can be applied whenever the answer space is monotonic. +

+ + + +
+ + + + diff --git a/Java/BinarySearch/BinarySearchOnAnswers/CapacitytoShipPackageswithinDDays.java b/Java/BinarySearch/BinarySearchOnAnswers/CapacitytoShipPackageswithinDDays.java new file mode 100644 index 00000000..ef904f9e --- /dev/null +++ b/Java/BinarySearch/BinarySearchOnAnswers/CapacitytoShipPackageswithinDDays.java @@ -0,0 +1,52 @@ +public class CapacitytoShipPackageswithinDDays { + public static void main(String args[]) + { + int[] weights={1,2,3,4,5,6,7,8,9,10}; + int days=5; + int result=shipWithinDays(weights,days); + System.out.println("The least weight capacity of the ship is : "+result); + + } + public static int shipWithinDays(int[] weights, int days) { + int left=0; + int right=0; + for(int weight:weights) + { + left=Math.max(left,weight); + right+=weight; + } + int answer=-1; + while(left<=right) + { + int mid=left+(right-left)/2; + if(canShip(weights,days,mid)) + { + answer=mid; + right=mid-1; + } + else{ + left=mid+1; + } + } + return answer; + } + public static boolean canShip(int[] weights,int days,int capacity) + { + int totalDays=1; + int currentLoad=0; + for(int weight:weights) + { + currentLoad+=weight; + if(currentLoad<=capacity) + { + continue; + } + else{ + totalDays++; + currentLoad=weight; + + } + } + return totalDays<=days; + } +} diff --git a/Java/BinarySearch/BinarySearchOnAnswers/FindthesmallestDivisor.java b/Java/BinarySearch/BinarySearchOnAnswers/FindthesmallestDivisor.java new file mode 100644 index 00000000..9b6e2e55 --- /dev/null +++ b/Java/BinarySearch/BinarySearchOnAnswers/FindthesmallestDivisor.java @@ -0,0 +1,64 @@ + +/* + +Find the Smallest Divisor Given a Threshold +Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and +divide all the elements of the array by it and sum the division results. Find the smallest divisor such that +the result is less than or equal to threshold. + +Input: nums = [1,2,5,9], threshold = 6 +Output: 5 + +Approach : Binary Search +To find the smallest divisor, we can use binary search on the range of possible divisors. +Time Complexity: O(n log m) // n is the length of the array, m is the maximum element in the array +Space Complexity: O(1) + + + + +*/ + + + +public class FindthesmallestDivisor { + public static void main(String args[]) + { + int[] nums={1,2,5,9}; + int threshold=6; + int result=findSmallestDivisor(nums,threshold); + System.out.println("The smallest divisor is : "+result); + + } + public static int findSmallestDivisor(int[] nums, int threshold) { + int left=1; + int right=0; + for(int num:nums) + { + right=Math.max(right,num); + } + int answer=-1; + while(left<=right) + { + int mid=left+(right-left)/2; + if(isPossible(nums,threshold,mid)) + { + answer=mid; + right=mid-1; + } + else{ + left=mid+1; + } + } + return answer; + } + public static boolean isPossible(int[] nums,int threshold,int divisor) + { + long sum=0; + for(int num:nums) + { + sum+=Math.ceil((double)num/divisor); + } + return sum<=threshold; + } +} diff --git a/Java/BinarySearch/BinarySearchOnAnswers/KokaEatingBanana.java b/Java/BinarySearch/BinarySearchOnAnswers/KokaEatingBanana.java new file mode 100644 index 00000000..252a2bdc --- /dev/null +++ b/Java/BinarySearch/BinarySearchOnAnswers/KokaEatingBanana.java @@ -0,0 +1,49 @@ + + //Binary Search on Answers + //monotonic function + //CanEat - > F F F T T T + //We need to find first T ( Minimum k) + + //Time Complexity - O(N log M) where N is number of piles and M is max pile size + //Space Complexity - O(1) + +public class KokaEatingBanana { + public static void main(String args[]) + { + int piles[]={3,6,7,11}; + int h=8; + + + int low=1; + int high=0; + for(int i=0;i=m; + } +} diff --git a/Java/BinarySearch/BinarySearchOnAnswers/SquareRoot.java b/Java/BinarySearch/BinarySearchOnAnswers/SquareRoot.java new file mode 100644 index 00000000..4cc591c8 --- /dev/null +++ b/Java/BinarySearch/BinarySearchOnAnswers/SquareRoot.java @@ -0,0 +1,47 @@ +package BinarySearchOnAnswers; + +public class SquareRoot { + public static void main(String args[]) + { + int n=4; + //Approach 1 : Linear Search + // TC : O(sqrt(n)) + + for(int i=0;i<=n;i++) + { + if(i*i==n) + { + System.out.println(i); + break; + } + } + + //Approach 2 : Binary Search + // TC : O(log n) + + int start=1; + int end=n; + int ans=-1; + + while(start<=end) + { + int mid=start+(end-start)/2; + int square=mid*mid; + if(square==n) + { + ans=mid; + break; + } + else if(square=x) + { + ans=mid; + end=mid-1; + } + else{ + start=mid+1; + } + } + return ans; + } + public static int floor(int arr[],int x) + { + int start=0; + int end=arr.length-1; + int ans=-1; + while(start<=end) + { + int mid=(start+end)/2; + if(arr[mid]<=x) + { + ans=mid; + start=mid+1; + } + else + { + end=mid-1; + } + } + return ans; + } +} diff --git a/Java/BinarySearch/Binary_On_1DArray/FindKthRotation.java b/Java/BinarySearch/Binary_On_1DArray/FindKthRotation.java new file mode 100644 index 00000000..e69de29b diff --git a/Java/BinarySearch/Binary_On_1DArray/FirstAndLastPositionOfElementInsSortedArray.java b/Java/BinarySearch/Binary_On_1DArray/FirstAndLastPositionOfElementInsSortedArray.java new file mode 100644 index 00000000..d9f50f50 --- /dev/null +++ b/Java/BinarySearch/Binary_On_1DArray/FirstAndLastPositionOfElementInsSortedArray.java @@ -0,0 +1,42 @@ +package Binary_On_1DArray; +class FirstAndLastPositionOfElementInsSortedArray { + public int[] searchRange(int[] nums, int target) { + int low=0; + int high=nums.length-1; + int mid; + int index=-1; + while(low<=high) + { + mid=low+(high-low)/2; + if(nums[mid]==target) + { + index=mid; + break; + } + if(nums[mid]>target) + { + high=mid-1; + } + else + { + low=mid+1; + } + } + if(index==-1) + { + return new int[]{-1,-1}; + } + + int first=index; + int last=index; + while(first>0 && nums[first-1]==target) + { + first--; + } + while(last= target) { + ans = mid; + end = mid - 1; + } else { + start = mid + 1; + } + } + return ans; + } +} diff --git a/Java/BinarySearch/Binary_On_1DArray/PeakElement.java b/Java/BinarySearch/Binary_On_1DArray/PeakElement.java new file mode 100644 index 00000000..70b1a472 --- /dev/null +++ b/Java/BinarySearch/Binary_On_1DArray/PeakElement.java @@ -0,0 +1,68 @@ + +// Constraints: + +// 1 <= nums.length <= 1000 +// -231 <= nums[i] <= 231 - 1 +// nums[i] != nums[i + 1] for all valid i. + +// + +public class PeakElement { + public static void main(String args[]) + { + //Approach one Linear Scan + //TC: 0(N) + //SC: O(1) + int arr[]={1,2,1,3,5,6,4}; + + for(int i=0;iarr[i+1]) + { + System.out.println("Peak Element is " + arr[i]); + break; + } + + + } + else if (i==arr.length-1) + { + if(arr[i]>arr[i-1]) + { + System.out.println("Peak Element is " + arr[i]); + break; + } + } + + else + { + if(arr[i]>arr[i-1] && arr[i]>arr[i+1]) + { + System.out.println("Peak Element is " + arr[i]); + break; + } + } + + //Approach 2 Binary Search + //TC: O(log N) + int start=0; + int end=arr.length-1; + while(startarr[mid+1]) + { + end=mid; + } + else + { + start=mid+1; + } + } + + + } + } +} diff --git a/Java/BinarySearch/Binary_On_1DArray/SearchInsertPosition.java b/Java/BinarySearch/Binary_On_1DArray/SearchInsertPosition.java new file mode 100644 index 00000000..fecaf2f7 --- /dev/null +++ b/Java/BinarySearch/Binary_On_1DArray/SearchInsertPosition.java @@ -0,0 +1,27 @@ +package Binary_On_1DArray; + +public class SearchInsertPosition { + + public int searchInsert(int[] nums, int target) { + int low=0; + int high=nums.length-1; + int mid; + while(low<=high) + { + mid=(low)+(high-low)/2; + if(nums[mid]==target) + { + return mid; + } + if (nums[mid]>target) + { + high=mid-1; + } + else + { + low=mid+1; + } + } + return low; + } +} \ No newline at end of file diff --git a/Java/BinarySearch/Binary_On_1DArray/SearchOneElementinSortedArray.class b/Java/BinarySearch/Binary_On_1DArray/SearchOneElementinSortedArray.class new file mode 100644 index 00000000..4a07a169 Binary files /dev/null and b/Java/BinarySearch/Binary_On_1DArray/SearchOneElementinSortedArray.class differ diff --git a/Java/BinarySearch/Binary_On_1DArray/SearchOneElementinSortedArray.java b/Java/BinarySearch/Binary_On_1DArray/SearchOneElementinSortedArray.java new file mode 100644 index 00000000..c4617e9b --- /dev/null +++ b/Java/BinarySearch/Binary_On_1DArray/SearchOneElementinSortedArray.java @@ -0,0 +1,18 @@ +package binary.on.onedarray; + +public class SearchOneElementinSortedArray { + public void findUniqueElement() { + int arr[] = {1, 1, 2, 3, 3, 4, 4, 5, 5}; + int low = 0; + int high = arr.length - 1; + while (low < high) { + int mid = (low + high) / 2; + if ((mid % 2 == 0 && arr[mid] == arr[mid + 1]) || (mid % 2 == 1 && arr[mid] == arr[mid - 1])) { + low = mid + 1; + } else { + high = mid; + } + } + System.out.println(arr[low]); + } +} diff --git a/Java/BinarySearch/Binary_On_1DArray/Search_In_Rotated_Sorted_Array.java b/Java/BinarySearch/Binary_On_1DArray/Search_In_Rotated_Sorted_Array.java new file mode 100644 index 00000000..af953036 --- /dev/null +++ b/Java/BinarySearch/Binary_On_1DArray/Search_In_Rotated_Sorted_Array.java @@ -0,0 +1,5 @@ +package Binary_On_1DArray; + +public class Search_In_Rotated_Sorted_Array { + +} diff --git a/Java/BinarySearch/Binary_On_1DArray/UpperBound.java b/Java/BinarySearch/Binary_On_1DArray/UpperBound.java new file mode 100644 index 00000000..5e40351e --- /dev/null +++ b/Java/BinarySearch/Binary_On_1DArray/UpperBound.java @@ -0,0 +1,28 @@ +package Binary_On_1DArray; +public class UpperBound { + public static void main(String args[]) + { + int arr[]={1,2,3,4,5,7,8,9}; + int x=6; + System.out.println(upperBound(arr,x)); + } + public static int upperBound(int arr[],int x) + { + int start=0; + int end=arr.length-1; + int ans=arr.length; + while(start<=end) + { + int mid=(end+start)/2; + if(arr[mid]>x) + { + ans=mid; + end=mid-1; + } + else{ + start=mid+1; + } + } + return ans; + } +}