Docsity

Binary_search_notes., Lecture notes of Data Structures and Algorithms

Toggle sidebar
bg1
Source: User-provided transcript
Binary Search –
Complete AI
Structured Notes
Binary Search is one of the most important searching algorithms
used in:
It is much faster than Linear Search when the data is sorted.
1. Introduction to Binary Search
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.
2. What is Searching?
Example:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

Partial preview of the text

Download Binary_search_notes. and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

Source: User-provided transcript

Binary Search –

Complete AI

Structured Notes

Binary Search is one of the most important searching algorithms used in:

It is much faster than Linear Search when the data is sorted.

1. Introduction to Binary Search

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.

2. What is Searching?

Example:

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:

for(int i = 0; i < n; i++) {

if(arr[i] == key)

return i;

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

Example:

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

  1. Binary Search Example**

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

else {

end = mid - 1;

mid = start + (end - start) / 2;

return -1;

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

int binarySearch(int arr[], int n, int key) {

int start = 0;

int end = n - 1;

while(start <= end) {

int mid = start + (end - start) / 2;

if(arr[mid] == key)

return mid;

else if(key > arr[mid])

start = mid + 1;

else

end = mid - 1;

return -1;

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)

Source: User-provided transcript (Love Babbar Binary Search

Problems Lecture)

1. Introduction

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!

2. Problem 1: First and Last Position of an

Element in Sorted Array

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

Example 1

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

Example 2

Array = [ 2 ] , K = 2 Output: 0 0

Example 3

3. Observation

Since array is sorted (^) → O(log n) solution using Binary Search is possible. (O(n) is easy, O(log n) is expected!)

4. Strategy

Split the problem into two parts: Part 1 Find: First Occurrence

Part 2 Find: Last Occurrence Then combine results.

5. Finding First Occurrence

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;

8. Finding Last Occurrence

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.

9. Conditions for Last 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;

10. Code: Last Occurrence

int lastOccurrence(int arr[], int n, int key) {

Memory Trick

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;

11. Difference Between First and Last

Occurrence

Condition First Occurrence Last Occurrence Found Key end = mid - 1 start = mid + 1 Goal Leftmost Rightmost

12. Total Number of Occurrences

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)

15. Problem 2: Peak Index in Mountain Array

Problem Statement Given: A Mountain Array. Find: Peak Element Index

16. What is a Mountain Array?

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

17. Important Observations

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]

18. Binary Search Idea

Exam Tip

Shortcut

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.

19. Peak Element Algorithm

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;

20. Code: Peak Index in Mountain Array

int peakIndexInMountainArray(vector& arr) { int start = 0;int end = arr.size() - 1; // Condition: start < end