{"id":18493262,"url":"https://github.com/aswinbarath/binary-search","last_synced_at":"2025-04-08T22:30:43.081Z","repository":{"id":49370497,"uuid":"405401899","full_name":"AswinBarath/Binary-Search","owner":"AswinBarath","description":"Problems based on Binary Search and various problem solving templates \u0026 patterns","archived":false,"fork":false,"pushed_at":"2024-03-02T07:33:48.000Z","size":1684,"stargazers_count":7,"open_issues_count":0,"forks_count":8,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-23T18:51:57.665Z","etag":null,"topics":["binary-search","java","problem-solving"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AswinBarath.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2021-09-11T14:34:31.000Z","updated_at":"2024-11-20T16:25:26.000Z","dependencies_parsed_at":"2024-02-27T22:49:47.110Z","dependency_job_id":null,"html_url":"https://github.com/AswinBarath/Binary-Search","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AswinBarath%2FBinary-Search","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AswinBarath%2FBinary-Search/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AswinBarath%2FBinary-Search/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AswinBarath%2FBinary-Search/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AswinBarath","download_url":"https://codeload.github.com/AswinBarath/Binary-Search/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247939787,"owners_count":21021844,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["binary-search","java","problem-solving"],"created_at":"2024-11-06T13:13:25.764Z","updated_at":"2025-04-08T22:30:38.051Z","avatar_url":"https://github.com/AswinBarath.png","language":"Java","readme":"# Binary Search\r\n\r\n### Binary Search Study Material \u0026 Resources\r\n\r\n- [SDE Sheet - 180 FAANG Problems (Striver)](https://takeuforward.org/interviews/strivers-sde-sheet-top-coding-interview-problems/)\r\n- [Kunal Kushwaha - Java + DSA + Interview Course](https://www.youtube.com/playlist?list=PL9gnSGHSqcnr_DxHsP7AW9ftq0AtAyYqJ)\r\n    - [Binary Search Algorithm - Theory + Code](https://youtu.be/f6UU7V3szVw?si=-k6FO1LpfBKjp0aJ)\r\n    - [Binary Search Interview Questions - Google, Facebook, Amazon](https://youtu.be/W9QJ8HaRvJQ?si=m-niAYVCe9UWiFbT)\r\n    - [Binary Search in 2D Arrays](https://youtu.be/enI_KyGLYPo?si=pgnP1C-vNRWV31yO)\r\n\r\n\r\n---\r\n\r\n\u003cdetails\u003e\r\n    \u003csummary\u003eProblems based on the Binary Search (Big List) (Goals Tracking)\u003c/summary\u003e\r\n    \u003cp\u003e\r\n\r\n### Problems based on the Binary Search (Big List) (Goals Tracking)\r\n\r\n- [x] [Steps used in Binary Search](#steps-used-in-binary-search)\r\n- [x] [Binary Search in Java](#binary-search-in-java)\r\n- [x] [Order-Agnostic Binary Search](#order-agnostic-binary-search)\r\n- [x] [When do we apply Binary Search ?](#when-do-we-apply-binary-search)\r\n- [x] Templates(Patterns) in Binary Search\r\n\t- [x] [Template I](./src/template_I/BinarySearchTemplate_I.java)\r\n\t- [x] [Template II](./src/template_II/BinarySearchTemplate_II.java)\r\n\t\u003c!-- - [x] [Template III](./src/template_III/BinarySearchTemplate_III.java) --\u003e\r\n- [ ] [Problems on Binary Search](#problems-on-binary-search)\r\n\t- [ ] Easy\r\n\t\t- [x] [Square Root](https://leetcode.com/problems/sqrtx/)\r\n\t\t- [x] [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/)\r\n\t\t- [x] [First Bad Version](https://leetcode.com/problems/first-bad-version/)\r\n\t\t- [ ] [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)\r\n\t\t- [ ] [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/)\r\n\t\t- [ ] [Arranging Coins(Easy)](https://leetcode.com/problems/arranging-coins/)\r\n\t\t- [x] [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/)\r\n\t\t- [x] [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/)\r\n\t\t- [x] [Search Insert Position](https://leetcode.com/problems/search-insert-position/)\r\n\t\t- [x] [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/)\r\n\t\t- [ ] [Count Negative Numbers in a Sorted Matrix](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/)\r\n\t\t- [ ] [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)\r\n\t\t- [ ] [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/)\r\n\t\t- [ ] [Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap/)\r\n\t\t- [ ] [Check If N and Its Double Exist](https://leetcode.com/problems/check-if-n-and-its-double-exist/)\r\n\t\t- [ ] [Special Array With X Elements Greater Than or Equal X](https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/)\r\n\t\t- [x] [Binary Search](https://leetcode.com/problems/binary-search/)\r\n\t- [ ] Medium\r\n\t\t- [x] [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/)\r\n\t\t- [x] [Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/)\r\n\t\t- [x] [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)\r\n\t\t- [x] [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)\r\n\t\t- [x] [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)\r\n\t\t- [x] [Find Peak Element](https://leetcode.com/problems/find-peak-element/)\r\n\t\t- [ ] [Find Right Interval](https://leetcode.com/problems/find-right-interval/)\r\n\t\t- [ ] [Reach a Number](https://leetcode.com/problems/reach-a-number/)\r\n\t\t- [ ] [Maximum Value at a Given Index in a Bounded Array](https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/)\r\n\t\t- [ ] [Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/)\r\n\t\t- [ ] [Minimum Absolute Sum Difference](https://leetcode.com/problems/minimum-absolute-sum-difference/)\r\n\t\t- [ ] [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/)\r\n\t\t- [ ] [Find a Peak Element II](https://leetcode.com/problems/find-a-peak-element-ii/)\r\n\t\t- [ ] [Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/)\r\n\t\t- [ ] [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)\r\n\t\t- [ ] [Capacity To Ship Packages Within D Days](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/)\r\n\t\t- [ ] [4 Sum](https://leetcode.com/problems/4sum/)\r\n\t- [ ] Hard\r\n\t\t- [ ] [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)\r\n\t\t- [x] [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)\r\n\t\t- [ ] [Aggressive cows](https://www.spoj.com/problems/AGGRCOW/)\r\n\t\t- [ ] [Book allocation](https://www.geeksforgeeks.org/allocate-minimum-number-pages/)\r\n\t\t- [ ] [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/)\r\n\t\t- [x] [Find in Mountain Array](https://leetcode.com/problems/find-in-mountain-array/)\r\n\t\t- [ ] [Count smaller number after Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)\r\n\t\t- [ ] [Divide Chocolate Problem](https://curiouschild.github.io/leetcode/2019/06/21/divide-chocolate.html)\r\n\r\n\r\n\u003c/p\u003e\r\n\u003c/details\u003e\r\n\r\n---\r\n\r\n\u003cdetails\u003e\r\n  \u003csummary\u003eBinary Search Problems (SDE Sheet - Day 11) (Striver) (Goals Tracking)\u003c/summary\u003e\r\n\u003cp\u003e\r\n\r\n### Binary Search Problems (SDE Sheet - Day 11) (Striver) (Goals Tracking)\r\n\r\n- Difficulity: Medium to Hard\r\n\r\n| Completion Status | Problems on Binary Search | Explanation | Solution |\r\n| --- | --- | --- | --- |\r\n| 🔃 | [Calculating n-th real root using binary search](https://www.geeksforgeeks.org/calculating-n-th-real-root-using-binary-search/) | [Brute, Better \u0026 Optimal Approaches](#) | [Java Soultion](./src/sde_sheet/.java) |\r\n| 🔃 | [Median in a row-wise sorted Matrix](https://practice.geeksforgeeks.org/problems/median-in-a-row-wise-sorted-matrix1527/1#) | [Brute, Better \u0026 Optimal Approaches](#) | [Java Soultion](./src/sde_sheet/.java) |\r\n| ✅ | [Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/) | [Brute, Better \u0026 Optimal Approaches](#) | [Java Soultion](./src/sde_sheet/SingleElementInSortedArray.java) |\r\n| ✅ | [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Approach](#8-search-in-rotated-sorted-array) | [Java Soultion](./src/sde_sheet/.java) |\r\n| 🔃 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [Brute, Better \u0026 Optimal Approaches](#) | [Java Soultion](./src/sde_sheet/.java) |\r\n| 🔃 | [K-th Element of Two Sorted Arrays](https://www.geeksforgeeks.org/k-th-element-two-sorted-arrays/) | [Brute, Better \u0026 Optimal Approaches](#) | [Java Soultion](./src/sde_sheet/.java) |\r\n| 🔃 | [Allocate Minimum Number of Pages](https://www.interviewbit.com/problems/allocate-books/) | [Brute, Better \u0026 Optimal Approaches](#) | [Java Soultion](./src/sde_sheet/.java) |\r\n| 🔃 | [Aggressive Cows](https://www.spoj.com/problems/AGGRCOW/) | [Brute, Better \u0026 Optimal Approaches](#) | [Java Soultion](./src/sde_sheet/.java) |\r\n\r\n\u003c/p\u003e\r\n\u003c/details\u003e\r\n\r\n---\r\n\r\n## Binary Search Notes\r\n\r\n**Condition: Array must be sorted**\r\n\r\n### Steps used in Binary Search (Algorithm)\r\n\r\n  - Find the middle element (Type 1)\r\n    - ( mid = ( start + end ) / 2 )\r\n  - Optimization for finding middle element (Type 2)\r\n    - mid = start + ( (end - start) / 2 )\r\n    - *Problem before: **Integer Overflow!!!** - might be possible that (start + end) exceeds the range of int in Java*\r\n  - If target \u003e mid =\u003e search in the right\r\n  - Else =\u003e search in left\r\n  - If middle element == target element =\u003e return (answer)\r\n\r\n### Binary Search in Java (Code)\r\n\r\n```\r\npackage com.aswin;\r\n\r\npublic class BinarySearch {\r\n\r\n    public static void main(String[] args) {\r\n        int[] arr = {-18, -12, -4, 0, 2, 3, 4, 15, 16, 18, 22, 45, 89};\r\n        int target = 3;\r\n        int ans = binarySearch(arr, target);\r\n        System.out.println(ans);\r\n    }\r\n\r\n    // return the index\r\n    // return -1 if it does not exist\r\n    static int binarySearch(int[] arr, int target) {\r\n        int start = 0;\r\n        int end = arr.length - 1;\r\n\r\n        while(start \u003c= end) {\r\n            // find the middle element\r\n            // int mid = (start + end) / 2;\r\n            // Problem: might be possible that (start + end) exceeds the range of int in Java\r\n\r\n            int mid = start + ( (end - start) / 2 );\r\n\r\n            if(target \u003c arr[mid]) {\r\n                end = mid - 1;\r\n            } else if (target \u003e arr[mid]) {\r\n                start = mid + 1;\r\n            } else {\r\n                // ans found\r\n                return mid;\r\n            }\r\n        }\r\n\r\n        return -1;\r\n    }\r\n\r\n}\r\n\r\n```\r\n\r\n### SafeGet Function in Binary Search (Important)\r\n\r\n- During Binary Search, when we access the array elements (at both ends) in search space, we must avoid **Array Index Out Of Bounds** Error.\r\n- So, always use the following function\r\n\r\n```\r\nint safeGet(int[] A, int i) {\r\n    if(0 \u003c= i \u0026\u0026 i \u003c A.length) {\r\n        return A[i];\r\n    } else {\r\n        return Integer.MAX_VALUE;\r\n    }\r\n}\r\n```\r\n\r\n---\r\n\r\n### Order-Agnostic Binary Search\r\n\r\n- When the array order is unknown ( ascending order or descending order ?)\r\n\r\n#### Steps for descending order\r\n\r\n- Find the middle element\r\n    - ( mid = ( start + end ) / 2 )\r\n- If target \u003e mid =\u003e search in the left\r\n- If target \u003c mid =\u003e search in right\r\n- Else middle element == target element (answer)\r\n\r\n#### So, How do we find the order?\r\n\r\n- Just check the start and end\r\n- **Steps** :\r\n    - if start \u003c end =\u003e Ascending order\r\n    - else =\u003e Descending order\r\n    \r\n#### Java Code - Order Agnostic Binary Search\r\n\r\n- One small change in Binary Search logic: **find whether the array is sorted in ascending or descending**\r\n    - `boolean isAsc = arr[start] \u003c arr[end]`\r\n\r\n```\r\npackage com.aswin;\r\n\r\npublic class OrderAgnosticBS {\r\n    public static void main(String[] args) {\r\n        int[] arr = {-18, -12, -4, 0, 2, 3, 4, 15, 16, 18, 22, 45, 89};\r\n        int target = 3;\r\n        int ans = orderAgnosticBS(arr, target);\r\n        System.out.println(ans);\r\n    }\r\n\r\n    // return the index\r\n    // return -1 if it does not exist\r\n    static int orderAgnosticBS(int[] arr, int target) {\r\n        int start = 0;\r\n        int end = arr.length - 1;\r\n\r\n        // find whether the array is sorted in ascending or descending\r\n        boolean isAsc = arr[start] \u003c arr[end];\r\n\r\n        while(start \u003c= end) {\r\n            // find the middle element\r\n            // int mid = (start + end) / 2;\r\n            // Problem: might be possible that (start + end) exceeds the range of int in Java\r\n\r\n            int mid = start + ( (end - start) / 2 );\r\n\r\n            if(arr[mid] == target) {\r\n                // ans found\r\n                return mid;\r\n            }\r\n            if(isAsc) {\r\n                if(target \u003c arr[mid]) {\r\n                    end = mid - 1;\r\n                } else {\r\n                    start = mid + 1;\r\n                }\r\n            }\r\n            else {\r\n                if(target \u003e arr[mid]) {\r\n                    end = mid - 1;\r\n                } else {\r\n                    start = mid + 1;\r\n                }\r\n            }\r\n\r\n        }\r\n\r\n        return -1;\r\n    }\r\n}\r\n\r\n```\r\n\r\n---\r\n\r\n### When do we apply Binary Search ?\r\n\r\n- Sorted array (If we are given as input)\r\n- When you are required to get one particular answer and you are following a continuous sequence to get the answer:\r\n    - Square Root of a number\r\n- Maximize the minimum answer\r\n- Minimize the maximum answer\r\n- Maximize the answer\r\n- Minimize the answer\r\n- much more ...\r\n\r\n---\r\n\r\n## Binary Search Problems w/ Dry Run, Breakdowns, \u0026 Code (Kunal Kushwaha)\r\n\r\n- Difficulity: Easy to Hard\r\n\r\n### 1. Ceiling of a number\r\n\r\n- **Ceiling of number**: Smallest element in array which is greater than or equal to target\r\n- Steps\r\n- 1. Find the closest or equal number to target\r\n- 2. Find all the numbers which are greater than the previous result (Binary Search)\r\n- 3. Return the smallest number from the previous category    \r\n---  \r\n- _Consider the following example:_\r\n- arr = [2, 3, 5, 9, 14, 16, 18], target = 14\r\n- ceiling(arr, target=14) = 14\r\n- ceiling(arr, target=15) = 16\r\n- ceiling(arr, target=4) = 5\r\n- ceiling(arr, target=9) = 9\r\n---\r\n- If target is found, return the **target**\r\n- Else return the **start**\r\n- Because when the condition is violated in the while loop: `start = end + 1`\r\n-       start  target  end              =\u003e              end  target  start\r\n- So the answer is not in this range, and the smallest element which is greater than or equal to target is the **start**\r\n\r\n---\r\n\r\n#### Java Code Link: [Ceiling of a number](./src/template_I/CeilingOfNumber.java)\r\n\r\n---\r\n\r\n\r\n### 2. Floor of a number\r\n\r\n- **Ceiling of number**: Greatest element in array which is smaller than or equal to target\r\n- Steps\r\n- 1. Find the closest or equal number to target\r\n- 2. Find all the numbers which are smaller than the previous result (Binary Search)\r\n- 3. Return the greatest number from the previous category\r\n---  \r\n- _Consider the following example:_\r\n- arr = [2, 3, 5, 9, 14, 16, 18], target = 14\r\n- floor(arr, target=4) = 3\r\n- floor(arr, target=9) = 9\r\n- floor(arr, target=14) = 14\r\n- floor(arr, target=19) = 18\r\n---\r\n- If target is found, return the **target**\r\n- Else return the **end**\r\n- Because when the condition is violated in the while loop: `start = end + 1`\r\n-       start  target  end              =\u003e              target  end  start\r\n- So the answer is not in this range, and the greatest element which is smaller than or equal to target is the **end**\r\n\r\n---\r\n\r\n#### Java Code Link: [Floor of a number - JavaCode](./src/template_I/CeilingOfNumber.java)\r\n\r\n---\r\n\r\n\r\n### 3. Find Smallest Letter Greater Than Target\r\n\r\n- Similar to Ceiling of a number\r\n- Change: Ignore mid == target condition\r\n- Change: Return start % arr.length as the result\r\n\r\n---\r\n\r\n#### LeetCode Link: [Find Smallest Letter Greater Than Target - LeetCode](https://leetcode.com/problems/find-smallest-letter-greater-than-target)\r\n\r\n#### Java Code Link: [Find Smallest Letter Greater Than Target - JavaCode](./src/template_I/FindSmallestLetterGreaterThanTarget.java)\r\n\r\n---\r\n\r\n\r\n### 4. Find First and Last Position of Element in Sorted Array `Facebook`\r\n\r\n- Apply Binary Search Twice:\r\n- Find the first occurrence of the target - Change: Update ans and end each time\r\n- Find the last occurrence of the target - Change: Update ans and start each time\r\n\r\n---\r\n\r\n#### LeetCode Link: [Find First and Last Position of Element in Sorted Array - LeetCode](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array)\r\n\r\n\r\n#### Java Code Link: [Find First and Last Position of Element in Sorted Array - JavaCode](./src/template_I/FindFirstAndLastPosition.java)\r\n\r\n---\r\n\r\n\r\n### [5. Find position of an element in a sorted array of infinite numbers](https://www.geeksforgeeks.org/find-position-element-sorted-array-infinite-numbers/) `Amazon`\r\n\r\n- In an infinte array of numbers, the size is unknown.\r\n- Binary search divides the array by two for each iteration following **Top - down approach**\r\n- For this problem, as we are unaware about the **end** pointer, we will follow **Bottom - up approach**\r\n- *Bottom-up* : Start with a small chunk of array and double up the size of the chunk by two for every iteration\r\n- Apply Binary search for each chunk and keep doubling the chunk until the element is found.\r\n\r\n---\r\n\r\n#### [Find position of an element in a sorted array of infinite numbers - JavaCode](./src/template_I/SearchInInfiniteSortedArray.java)\r\n\r\n---\r\n\r\n\r\n### 6. Peak Index in Mountain Array\r\n\r\n- Mountain Array is also known as **Bitonic array**.\r\n- In this array, the numbers in first part are sorted in increasing order and the second part in decreasing order.\r\n- Peak element is nothing but the maximum element in the array.\r\n- So, we have two cases where we can compare adjacent elements:\r\n\t- **Ascending part** where we can update the start = mid + 1\r\n\t- **Descending part** where we can update the end = mid\r\n\r\n- In the end, **start == end** and pointing to the largest number because of the 2 checks above\r\n- start and end are always trying to find the max element in the above 2 checks\r\n- Hence, when they are pointing to just one element, that is the max one because that is what the checks say\r\n- More elaboration: at every point of the time for start and end, \r\n- they have the best possible answer till that time and if we are saying that only one item is remaining\r\n- hence because of above line that is the best possible ans\r\n\r\n---\r\n\r\n#### [Peak Index in Mountain Array - JavaCode](./src/template_II/PeakIndexinMountainArray.java)\r\n\r\n---\r\n\r\n#### [Peak Index in Mountain Array - LeetCode](https://leetcode.com/problems/peak-index-in-a-mountain-array/)\r\n\r\n---\r\n\r\n#### [Find Peak Element - LeetCode](https://leetcode.com/problems/find-peak-element/)\r\n\r\n---\r\n\r\n\r\n### 7. Find in Mountain Array\r\n\r\n- Similar to Peak Index in Mountain Array, except the **target** is given\r\n- Here, we can first find the *Peak Index*\r\n- Then, apply Order Agnostic Binary Search in both parts of the Mountain array:\r\n\t- `0 -\u003e peakIndex`\r\n\t- `peakIndex+1 -\u003e arr.length - 1`\r\n- And, finally return the answer\r\n\r\n---\r\n\r\n#### [Find in Mountain Array - JavaCode](./src/template_II/FindInMountainArray.java)\r\n\r\n---\r\n\r\n#### [Find in Mountain Array - LeetCode](https://leetcode.com/problems/find-in-mountain-array/)\r\n\r\n---\r\n\r\n\r\n### 8. Search in Rotated Sorted Array\r\n#### `Amazon`, `Google`\r\n\r\n#### Rotated Array:\r\n- Consider an array = `[2, 4, 5, 7, 8, 9, 10, 12]`\r\n- After 1st rotation, array = `[12, 2, 4, 5, 7, 8, 9, 10]`\r\n- After 2nd rotation, array = `[10, 12, 2, 4, 5, 7, 8, 9]`\r\n\r\n---\r\n\r\n#### Approach: Find the pivot in the array\r\n- pivot is from where your next numbers are ascending\r\n- **pivot** is also the largest number\r\n- For example: `[3, 4, 5, 6, 7, 0, 1, 2]`\r\n\t- Here, the is pivot = 7\r\n\t- Both parts before \u0026 after the pivot is sorted in ascending order\r\n- So, we can follow the following steps:\r\n\t- Find pivot\r\n\t- Search target in first half =\u003e Simple BS `(0 -\u003e pivot)`\r\n\t- If still not found, search target in second half =\u003e Simple BS `(pivot+1, end)`\r\n- Now, the problem is to find the pivot:\r\n\t- Consider `[3, 4, 5, 6, 7, 0, 1, 2]`\r\n\t- We can observe that only two elements `7, 0` are descending\r\n\t- So, when do we find the answer:\r\n\t\t- Case 1: When mid \u003e mid+1 element, then mid is the pivot\r\n\t\t- Case 2: When mid \u003c mid-1 element, then mid-1 is the pivot\r\n\t\t- Case 3: When start \u003e= mid element, then end = mid - 1\r\n\t\t- Case 4: When start \u003c mid element, then start = mid + 1\r\n\t\t- ( Explanation for case 3 \u0026 4: if mid was pivot it would've returned by case 1 \u0026 2... )\r\n\t\t- ( Hence, proved that bigger number lies behind in case 3 and ahead in case 4, so ignore mid in case 3 and 4 using mid (+ or -) 1 )\r\n- Now, we have to find the target:\r\n\t- If target == arr[pivot] return pivot\r\n\t- If target \u003e= arr[0], Search target in first half =\u003e Simple BS `(0 -\u003e pivot)`\r\n\t- If target \u003c arr[pivot] search target in second half =\u003e Simple BS `(pivot+1, end)`\r\n\r\n---\r\n\r\n#### [Search in Rotated Sorted Array - JavaCode](./src/template_I/SearchRotatedSortedArray.java)\r\n\r\n---\r\n\r\n#### [Search in Rotated Sorted Array - LeetCode](https://leetcode.com/problems/search-in-rotated-sorted-array/)\r\n\r\n---\r\n\r\n\r\n### 9. Search in Rotated Sorted Array with duplicates\r\n\r\n- The approach for duplicates are same as the previous problem except\r\n\t- The while loop should terminate when start\u003e=end\r\n\t- The Case 3 \u0026 4 will not work for duplicates\r\n\t\r\n- So, we can skip the duplicates by comparing start, mid and end only if they are not pivot elements\r\n- And then we can start reducing the search space based on the comparision of start, mid, and end\r\n\r\n\r\n---\r\n\r\n#### [Search in Rotated Sorted Array with duplicates - JavaCode](./src/template_I/SearchRotatedSortedArray.java)\r\n\r\n---\r\n\r\n#### [Search in Rotated Sorted Array with duplicates - LeetCode](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)\r\n\r\n---\r\n\r\n\r\n### 10. Find the Rotation Count in Rotated Sorted Array\r\n\r\n- Similar to previous approaches except\r\n\t- We return 0 if array's pivot is -1\r\n\t- Else we return the pivot+1 as the answer\r\n- Because the array rotates pivot times, and as we get 0-indexed pivot, we return pivot+1 as the answer.\r\n\r\n\r\n---\r\n\r\n#### [Find the Rotation Count in Rotated Sorted Array - JavaCode](./src/template_I/FindRotationCountInRotatedSortedArray.java)\r\n\r\n---\r\n\r\n#### [Find the Rotation Count in Rotated Sorted Array - GFG](https://www.geeksforgeeks.org/find-rotation-count-rotated-sorted-array/)\r\n\r\n---\r\n\r\n\r\n### 11. Split Array Largest Sum  \r\n#### `Google`, `Leetcode Hard Problem` \r\n\r\n- Find the minimum (minAns) and maximum no. of splits (maxAns) we can make  \r\n- Take the minAns and maxAns as start and end respectively\r\n- Apply binary search such that\r\n    - the mid will be (minAns + maxAns) / 2\r\n    - Traverse the array and calculate the cummulative sum to calculate how many pieces you can divide the array with this mid (max sum)\r\n        - if sum becomes greater than mid, then reset sum to current number, and increment the no. of pieces\r\n        - else continue adding sum\r\n    - Now, apply checks for binary search\r\n        - If no. of pieces are greater than `m` (given no. of partitions) then update start = end + 1\r\n        - Else update end = mid\r\n\r\n---\r\n\r\n\u003cimg src=\"assets/Split Array Largest Sum 1.jpg\" alt=\"Split Array Largest Sum 1\" width=\"400px\" \u003e\r\n\r\n\u003cimg src=\"assets/Split Array Largest Sum 2.jpg\" alt=\"Split Array Largest Sum 2\" width=\"400px\" \u003e\r\n\r\n\u003cimg src=\"assets/Split Array Largest Sum 3.jpg\" alt=\"Split Array Largest Sum 3\" width=\"400px\" \u003e\r\n\r\n---\r\n\r\n#### [Split Array Largest Sum - JavaCode](./src/binary_search_problems/SplitArrayLargestSum.java)\r\n\r\n#### [Split Array Largest Sum - LeetCode](https://leetcode.com/problems/split-array-largest-sum/)\r\n\r\n---\r\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faswinbarath%2Fbinary-search","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faswinbarath%2Fbinary-search","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faswinbarath%2Fbinary-search/lists"}