















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
















Source: User-provided transcript
Binary Search is one of the most important searching algorithms used in:
It is much faster than Linear Search when the data is sorted.
MOST IMPORTANT
ā Coding interviews ā Online assessments ā Competitive programming ā Data Structures & Algorithms
Searching means finding whether a particular element ( key ) exists in a collection of data.
Array = [3, 7, 0, -2, 5, 9] Key = 2 We need to determine whether 2 exists in the array.
Check every element one by one until:
3. Linear Search Recap
Working
ā Element is found ā Array ends
3 ā 7 ā 0 ā -2 ā 5 ā 9 Compare each element with key = 2. Result: Not Found
Linear Search Algorithm
The array must be:
Binary Search works only on: Monotonic Data
ā Sorted in Increasing Order: [1, 3, 5, 7, 9] ā OR ā Sorted in Decreasing Order: [9, 7, 5, 3, 1]
Find middle element. ā Compare middle element with key. ā Discard half of the search space. ā Repeat on remaining half.
Instead of searching every element, we eliminate half of them in each step!
**6. Core Idea of Binary Search
Array: [3, 5, 9, 13, 27]
Key: 13 Indexes: 0 1 2 3 4 Step 1: Find Mid mid = (0 + 4)/2 = 2 Element: arr[2] = 9 Compare: 13 > 9 ā Move Right. Step 2: New Search Space [13, 27] Indexes: 3, 4 Find Mid: mid = (3 + 4)/2 = 3 Element: arr[3] = 13 ā Found. Return: 3
8. Binary Search Logic
MOST IMPORTANT
ā Case 1: arr[mid] == key ā Return index. Case 2: key > arr[mid] ā Search Right Half. start = mid + 1;
Case 3: key < arr[mid] ā Search Left Half. end = mid - 1;
9. Binary Search Algorithm
Potential Problem: mid = (start + end)/2; Suppose: start = 2^31 - 1; end = 2^31 - 1; Then: start + end can exceed integer range. This causes: Integer Overflow
11. Why Not Use (start +
end)/2?
COMMON MISTAKE
Use: mid = start + (end - start)/2;
12. Safe Mid Formula
EXAM TIP
Advantages:
ā Prevents overflow ā Industry standard ā Used in interviews
13. Binary Search Dry Run
(Element Present)
Array: [3, 7, 11, 13, 19, 27] Key: 27 Iteration 1: mid = 2, value = 11 ā Move Right. Iteration 2: mid = 4, value = 19 ā Move Right. Iteration 3: mid = 5, value = 27 ā Found. Return: 5
14. Binary Search Dry Run
(Element Absent)
Array: [5, 11, 13, 17, 19, 27] Key: 25 Iteration 1: mid = 2, value = 13 ā Move Right. Iteration 2: mid = 4, value = 19 ā Move Right. Iteration 3: mid = 5, value = 27 ā Move Left. No search space remains. ā Return: -
MOST IMPORTANT
17. Binary Search Template
(Interview Ready)
FREQUENTLY ASKED
18. Important Interview Points
Must Remember: ā Array must be sorted ā ā Works on increasing or decreasing order arrays ā ā Search space halves every iteration ā ā Time Complexity = O(log n) ā ā Space Complexity = O(1) ā ā Use safe mid formula: start + (end - start)/2 ā ā Return -1 if element not found ā
Binary Search is the foundation of many advanced problems:
Lower Bound Upper Bound First Occurrence
Last Occurrence Count Occurrences
Search in Rotated Sorted Array Pivot Element
Book Allocation Problem Aggressive Cows Problem
Roti/Paratha Problems Binary Search on Answer
Peak Element Problems
19. Applications of Binary
Search
MOST IMPORTANT
QUICK REVISION
Binary Search Problems ā AI Structured Notes (Part 2)
After learning: š Binary Search Theory š Binary Search Code š Binary Search Implementation The next step is solving Binary Search Problems. Topics Covered First Occurrence of an Element Last Occurrence of an Element Total Number of Occurrences Peak Element in Mountain Array Pivot Element in Rotated Array (Homework) Search in Rotated Sorted Array
Must Master Basics!
Problem Statement Given: A sorted array, A key K Find: First occurrence (Leftmost) & Last occurrence (Rightmost) If element does not exist: Return {-1, -1}
Array = [ 0 , 5 , 5 , 6 , 6 , 6 ] , K = 3 Output: -1 -1 ... Because 3 does not exist
Array = [ 0 , 0 , 1 , 1 , 2 , 2 , 2 , 2 ] , K = 2 Indexes: 0 1 2 3 4 5 6 7 Output: 4 7 Because: First occurrence = index 4 , Last occurrence = index 7
Array = [ 2 ] , K = 2 Output: 0 0
Since array is sorted (^) ā O(log n) solution using Binary Search is possible. (O(n) is easy, O(log n) is expected!)
Split the problem into two parts: Part 1 Find: First Occurrence
Part 2 Find: Last Occurrence Then combine results.
Example Array = [ 1 , 2 , 3 , 3 , 5 ] , Key = 3 Indexes: 0 1 2 3 4
Look Closely
} else if(arr[mid] < key) {start = mid + 1; } else { end = mid - 1; // arr[mid] > key } } } return ans;
Same logic as First Occurrence. Only one change. When Key Found Instead of moving left (^) ā end = mid - 1; Move right (^) ā start = mid + 1; Because we need the rightmost occurrence.
Case 1: arr[mid] == key Action: ans = mid; start = mid + 1;
Case 2: arr[mid] < key Search Right: start = mid + 1;
Case 3: arr[mid] > key Search Left: end = mid - 1;
int lastOccurrence(int arr[], int n, int key) {
int start = 0;int end = n - 1; int ans = -1; while(start <= end) { int mid = start + (end - start)/2; if( arr[mid] == key // Found? Store and look right ) { start = mid + 1;^ ans = mid; } else if(arr[mid] < key) {start = mid + 1; } else { end = mid - 1; // arr[mid] > key } } } return ans;
Condition First Occurrence Last Occurrence Found Key end = mid - 1 start = mid + 1 Goal Leftmost Rightmost
Problem Array = [ 1 , 2 , 3 , 3 , 3 , 3 , 5 ] , Key = 3 Find: How many times 3 occurs?
First Occurrence (^) ā 2 Last Occurrence (^) ā 5
Total Occurrence (^) ā O(log n) Because: O(log n) + O(log n) = O(log n)
Problem Statement Given: A Mountain Array. Find: Peak Element Index
A mountain array: Increasing Part arr[i] < arr[i+1] followed by Decreasing Part arr[i] > arr[i+1]
Example [0,10,5,2] (^) ā Peak: 10 Example [3,4,5,1] (^) ā Peak: 5
[ 0 , 1 , 0 ] Graph: / ^1 0 0
[ 0 , 2 , 1 , 0 ] Graph: (^2) / (^0 1) 0
Left Slope arr[i] < arr[i+1] (^) ā Increasing. Right Slope arr[i] > arr[i+1] (^) ā Decreasing. Peak Element arr[i] > arr[i-1] and arr[i] > arr[i+1]
Take: mid Check: arr[mid] < arr[mid+1] If True (^) ā You are on Left Slope. Peak lies on Right Side. Move: start = mid + 1;
Else (^) ā You are either: 1) On Right Slope , or 2) On Peak. Move: end = mid; Important: NOT end = mid - 1 Because: mid itself may be the peak.
start = 0 end = n- while ( start < end ) { mid = start + (end-start)/ if ( arr[mid] < arr[mid+1] ) start = mid + 1; else end = mid; } return start;
int peakIndexInMountainArray(vector& arr) { int start = 0;int end = arr.size() - 1; // Condition: start < end