Introduction to Binary Search (Data Structures & Algorithms #10)

CS Dojo · Beginner ·⚡ Algorithms & Data Structures ·5y ago

Key Takeaways

This video teaches the binary search algorithm for efficient searching

Full Transcript

hey everyone in this video i'm gonna give you a quick introduction to binary search and i'm gonna explain how it works with some samba code and at the end of the video i'm also gonna show you what i would say is a medium difficulty problem which you can solve with binary search so suppose you're given a sorted array of integers for example this one you're also given a target integer for example this one and your task here is to find the target in the array and that's a problem you can solve with binary search and let's say here that you need to write a function called search that takes these two arguments the array and the target and returns the index of the target if the target exists in the array and if it doesn't this function should return -1 instead so in this particular example your function should return 6 because the index of the target integer 11 right here is 6. and one approach you can use to solve this problem as a comparison to binary search is called linear search the idea of this approach is you start at the beginning of the array this one right here and then check if it's our target or not and if it's not our target then we go to the next element and the next element zone until we find our target or we don't find our target but find a number that's larger than the target then we can stop the search then and this approach has the time complexity of of and where n is the number of elements in the array and that's because assuming that we don't know where the target is we're going to check you know a certain number of elements in the array and on average we'll need to check about half the elements because on average you know we can assume that the target is going to be in the middle of the array and so we'll need to check n over two elements on average and that's why we have of n over two in time which is equivalent to o of n okay so as a better faster alternative to linear search let's take a look at a binary search and to see how it works we're going to use this example of a sorted array of integers ranging from minus 50 to 50. and as you can see we have 40 integers here we're also given the integer target of 20. now the first step in binary search is to say if the target exists in this array it must be between the first element this element right here and the last element this element right here another way to say the same thing would be to say our initial search region is going to be this entire array which is between the first element and the last element we can express the idea by defining two integer variables or two uh pointers which we're going to call left and right or l and r so l would be zero pointing at this element right here and r would be pointing this last element right here and in this particular example the initial value of r would be 39 because the length of the array is 40 right here okay and the next step in binary search would be to check the number that's in the middle of l and r in this particular case that's this number right here and let's say as an example that it happens to be 10. then at that point since our target is larger than 10 we'll know that the target if it exists in this array must be in this region right here so that means we can move our left pointer or l over here and then we can keep repeating the same procedure to narrow our region more and more so we can check the number in the middle of the new value of l and the current value of r that's this number right here and if that happens to be larger than target that's 30 right here then we'll know our target must be between this current value of l and this element right here so we can move r over here so just like that we can keep repeating the same procedure until the number between l and r uh the number in the middle of l and r happens to be the target at that point we can uh finish running our function because we've already found that number or uh when r comes to the left of l kind of like that and that's because at that point our search region is empty so that means that this target number doesn't exist in this array okay so we're going to put this idea into code but first before that let's think about the time complexity of this approach well with this particular example that we just saw our search region started with 40 elements and then it became about 20 and then about 10 and so on until we got down to one so the pattern we see here is we start uh with a search region of n elements which is the number of elements in the given array and then we have it and then we get the we get half of that and half of that and so on until we get one and i can write it uh slightly differently just like that so we have n and then n over two and over 2 to the power of 2 and so on until n over 2 to the power of x is roughly equal to 1 whatever this x is and now for a second let's say that n happens to be 8 that's 2 to the power 3 so this expression right here n over 2 to the power 3 becomes one so that means if n happens to be eight we'll need to check about uh three elements about three elements until our search region becomes one you might say well that's more like four elements but i'm saying the number of elements that we need to check is roughly equal to three so what i just showed you here is that when n is equal to 2 to the power 3 we'll need to check about three elements and for this algorithm to be complete so if n is uh roughly equal to 2 to the power of x then we'll need to check about x elements so basically to find the number of elements that we need to check we only need to find x such that 2 to the power of x is roughly equal to n and if you solve this for x of course you get x being roughly equal to log 2 of n and so the time complexity of this algorithm will be o of the number of elements that we need to check which is of log 2 of n and you can rewrite it as of log n for short okay so what i showed you here is not an exact mathematical proof but i hope that at least this logic is clear enough to you anyway as an example if you had 10 million elements in the given array then the number of elements that we need to check will be roughly equal to log 2 of 10 million which is 23.253 and so on which is about 24. so if you had 10 million elements in the given sortie array you need to check almost about 24 elements to find the target uh number that you're given now we're going to put our approach into actual code and to do that we're going back to our smaller example that we saw at the beginning of this video we just have eight elements in this array and we're also given the target of let's say 11 and we're trying to write our function search that takes these two arguments and by the way i'm going to show you some suit code that looks like python here but you'll be able to find the actual python and java code that i wrote for this at this url anyway the first step in this code is defining our left and right pointer left or l will be zero right here and right or r will be the array's length minus one so the array's length is 8 here and so r will be 7 and then after that we'll run a while loop saying while left is less than or equal to right or in other words while right is not to the left of l and we'll say while that condition holds we'll first need to find the mid index and that's going to be between left and right and that's going to be the average of left and right so left plus right divided by 2 and if this is not an integer you can round it down to get an integer value here and so in this particular example we'll get zero plus seven divided by two which is three point five round it down and we get three so mid will be 3 right here and the next step after that will be to say if that element r of mid happens to be the target then we've found the target so we're going to return that index mid and else if target happens to be less than that element right there so if the target happens to be for example six in this example then the right pointer will be mid minus one so the right pointer will move right there and otherwise target is greater than that element right here so that's the example we have right here target happens to be greater than seven so then left or l uh will be mid plus 1 that's right here and then we can keep repeating this while loop until we either find r of mid to be target and at that point we can return mid or left will be greater than right so for example if the target happens to be let's say 12 which doesn't exist in this array then eventually l will come to the right of r or in other words left will be greater than right so at that point we'll get out of the while loop and then we can return -1 to show that the target doesn't exist in this array okay so that's how binary search works but if you're looking for extra practice i would recommend using my business affiliates product i'll algoexpert.io which you can find at this referral link of mine and get a discount from with my discount code csdojo they have two related problems one is simply implementing binary search and the second one is called shifty binary search which i think is much more interesting so in this problem uh you're given a sorted array as well as a target and you need to find the position of the target with a little bit of twist you could be given a sorted array just like that but you could also be given an array that's sorted but also shifted so if you're given for example this array and the target uh you can see that it's sorted but shifted by one just like that or you could be given this array uh which is the same array but shifted by a larger amount just like that and you don't know how much your array has been shifted by when you're given this problem so you know the problem is writing a function that takes these two arguments one of these arrays as well as the target and returns the index of the target if it exists and minus one if it doesn't you should be able to solve it and of log n anyway i personally think this is a pretty interesting problem i had a lot of fun when i was solving it so i would say try solving it yourself and if you want to practice implementing it on an interactive environment uh you can check out aqua experts website and they have a lot of other problems too like 98 other problems on a variety of different topics in data structures and algorithms anyway thank you as always for watching my videos and i'll see you guys in the next one

Original Description

Here’s my introduction to the binary search algorithm. Check out the practice problem from https://algoexpert.io/csdojo at 12:17. You can find my Python and Java sample code at: https://www.csdojo.io/binary Also join our community at: https://www.csdojo.io/community
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from CS Dojo · CS Dojo · 0 of 60

← Previous Next →
1 4 Hacks for Finding the Optimal Answer in Coding Interview QUICKLY!
4 Hacks for Finding the Optimal Answer in Coding Interview QUICKLY!
CS Dojo
2 Dynamic Programming Tutorial with Fibonacci Sequence
Dynamic Programming Tutorial with Fibonacci Sequence
CS Dojo
3 Kadane's Algorithm to Maximum Sum Subarray Problem
Kadane's Algorithm to Maximum Sum Subarray Problem
CS Dojo
4 Longest Common Subsequence (Dynamic Programming)
Longest Common Subsequence (Dynamic Programming)
CS Dojo
5 0-1 Knapsack Problem (Dynamic Programming)
0-1 Knapsack Problem (Dynamic Programming)
CS Dojo
6 Amazon Coding Interview: Count Negative Integers in Row/Column-Wise Sorted Matrix
Amazon Coding Interview: Count Negative Integers in Row/Column-Wise Sorted Matrix
CS Dojo
7 Microsoft Coding Interview Question and Answer: Lowest Common Ancestor
Microsoft Coding Interview Question and Answer: Lowest Common Ancestor
CS Dojo
8 Learn Counting Sort Algorithm in LESS THAN 6 MINUTES!
Learn Counting Sort Algorithm in LESS THAN 6 MINUTES!
CS Dojo
9 Radix Sort Algorithm Introduction in 5 Minutes
Radix Sort Algorithm Introduction in 5 Minutes
CS Dojo
10 Coding Interview Question and Answer: Longest Consecutive Characters
Coding Interview Question and Answer: Longest Consecutive Characters
CS Dojo
11 Coding Interview: Can You RANDOMLY Reorder Array in O(N)?
Coding Interview: Can You RANDOMLY Reorder Array in O(N)?
CS Dojo
12 Coding Interview Question: Tower Hopper Problem
Coding Interview Question: Tower Hopper Problem
CS Dojo
13 Problem Solving Technique #1 for Coding Interviews with Google, Amazon, Microsoft, Facebook, etc.
Problem Solving Technique #1 for Coding Interviews with Google, Amazon, Microsoft, Facebook, etc.
CS Dojo
14 Google Coding Interview Question and Answer #1: First Recurring Character
Google Coding Interview Question and Answer #1: First Recurring Character
CS Dojo
15 Facebook Coding Interview Question and Answer #1: All Subsets of a Set
Facebook Coding Interview Question and Answer #1: All Subsets of a Set
CS Dojo
16 Think you're not smart enough to work at Google? Well, think again.
Think you're not smart enough to work at Google? Well, think again.
CS Dojo
17 How to Crack a Google Coding Interview - An Ex-Googler’s Guide
How to Crack a Google Coding Interview - An Ex-Googler’s Guide
CS Dojo
18 Amazon Coding Interview Question - K Closest Points to the Origin
Amazon Coding Interview Question - K Closest Points to the Origin
CS Dojo
19 How I Got an Internship at Microsoft
How I Got an Internship at Microsoft
CS Dojo
20 How I Got a Job at Google as a Software Engineer (without a Computer Science Degree!)
How I Got a Job at Google as a Software Engineer (without a Computer Science Degree!)
CS Dojo
21 Why I Left My $100,000+ Job at Google
Why I Left My $100,000+ Job at Google
CS Dojo
22 Top 5 Programming Languages to Learn to Get a Job at Google, Facebook, Microsoft, etc.
Top 5 Programming Languages to Learn to Get a Job at Google, Facebook, Microsoft, etc.
CS Dojo
23 How I Learned to Code - and Got a Job at Google!
How I Learned to Code - and Got a Job at Google!
CS Dojo
24 Why I Left Google To Be A YouTuber FULL-TIME (and NOT part-time!)
Why I Left Google To Be A YouTuber FULL-TIME (and NOT part-time!)
CS Dojo
25 What Is Dynamic Programming and How To Use It
What Is Dynamic Programming and How To Use It
CS Dojo
26 Python Tutorial for Absolute Beginners #1 - What Are Variables?
Python Tutorial for Absolute Beginners #1 - What Are Variables?
CS Dojo
27 What's It Really Like To Intern At Google? (LIVE with a former Google software engineer intern)
What's It Really Like To Intern At Google? (LIVE with a former Google software engineer intern)
CS Dojo
28 How to Use If Else Statements in Python (Python Tutorial #2)
How to Use If Else Statements in Python (Python Tutorial #2)
CS Dojo
29 Dynamic Programming Interview Question #1 - Find Sets Of Numbers That Add Up To 16
Dynamic Programming Interview Question #1 - Find Sets Of Numbers That Add Up To 16
CS Dojo
30 How To Use Functions In Python (Python Tutorial #3)
How To Use Functions In Python (Python Tutorial #3)
CS Dojo
31 What’s It Like To Be A Program Manager Intern At Microsoft? (LIVE with a former Microsoft intern)
What’s It Like To Be A Program Manager Intern At Microsoft? (LIVE with a former Microsoft intern)
CS Dojo
32 Introduction To Lists In Python (Python Tutorial #4)
Introduction To Lists In Python (Python Tutorial #4)
CS Dojo
33 Introduction to For Loops in Python (Python Tutorial #5)
Introduction to For Loops in Python (Python Tutorial #5)
CS Dojo
34 What Programming Language Should I Learn First?
What Programming Language Should I Learn First?
CS Dojo
35 What Is Competitive Programming and How To Prepare For It (LIVE with Gaurav Sen)
What Is Competitive Programming and How To Prepare For It (LIVE with Gaurav Sen)
CS Dojo
36 While Loops and The Break Statement in Python (Python Tutorial #6)
While Loops and The Break Statement in Python (Python Tutorial #6)
CS Dojo
37 More About For Loops in Python & Solutions to the Last 2 Problems (Python Tutorial #7)
More About For Loops in Python & Solutions to the Last 2 Problems (Python Tutorial #7)
CS Dojo
38 How to Learn to Code - Best Resources, How to Choose a Project, and more!
How to Learn to Code - Best Resources, How to Choose a Project, and more!
CS Dojo
39 How To Use Dictionaries In Python (Python Tutorial #8)
How To Use Dictionaries In Python (Python Tutorial #8)
CS Dojo
40 Data Structures & Algorithms #1 - What Are Data Structures?
Data Structures & Algorithms #1 - What Are Data Structures?
CS Dojo
41 An Overview of Arrays and Memory (Data Structures & Algorithms #2)
An Overview of Arrays and Memory (Data Structures & Algorithms #2)
CS Dojo
42 Introduction to Classes and Objects - Part 1 (Data Structures & Algorithms #3)
Introduction to Classes and Objects - Part 1 (Data Structures & Algorithms #3)
CS Dojo
43 Classes and Objects with Python - Part 1 (Python Tutorial #9)
Classes and Objects with Python - Part 1 (Python Tutorial #9)
CS Dojo
44 Introduction to Classes and Objects - Part 2 (Data Structures & Algorithms #4)
Introduction to Classes and Objects - Part 2 (Data Structures & Algorithms #4)
CS Dojo
45 Classes and Objects with Python - Part 2 (Python Tutorial #10)
Classes and Objects with Python - Part 2 (Python Tutorial #10)
CS Dojo
46 Introduction to Linked Lists (Data Structures & Algorithms #5)
Introduction to Linked Lists (Data Structures & Algorithms #5)
CS Dojo
47 Introduction to Recursion (Data Structures & Algorithms #6)
Introduction to Recursion (Data Structures & Algorithms #6)
CS Dojo
48 Introduction to Big O Notation and Time Complexity (Data Structures & Algorithms #7)
Introduction to Big O Notation and Time Complexity (Data Structures & Algorithms #7)
CS Dojo
49 Amazon Coding Interview Question - Recursive Staircase Problem
Amazon Coding Interview Question - Recursive Staircase Problem
CS Dojo
50 Using Boolean in Python (Python Tutorial #11)
Using Boolean in Python (Python Tutorial #11)
CS Dojo
51 Intro to Data Analysis / Visualization with Python, Matplotlib and Pandas | Matplotlib Tutorial
Intro to Data Analysis / Visualization with Python, Matplotlib and Pandas | Matplotlib Tutorial
CS Dojo
52 What Can You Do with Python? - The 3 Main Applications
What Can You Do with Python? - The 3 Main Applications
CS Dojo
53 Facebook Coding Interview Question - How Many Ways to Decode This Message?
Facebook Coding Interview Question - How Many Ways to Decode This Message?
CS Dojo
54 List Comprehension Basics with Python (Python Tutorial #12)
List Comprehension Basics with Python (Python Tutorial #12)
CS Dojo
55 How To Use Sets in Python (Python Tutorial #13)
How To Use Sets in Python (Python Tutorial #13)
CS Dojo
56 Python books for beginners? What Python projects to work on? | 2 Python Beginner FAQ’s!
Python books for beginners? What Python projects to work on? | 2 Python Beginner FAQ’s!
CS Dojo
57 Resources for Learning Data Structures and Algorithms (Data Structures & Algorithms #8)
Resources for Learning Data Structures and Algorithms (Data Structures & Algorithms #8)
CS Dojo
58 6 Python Exercise Problems for Beginners - from CodingBat (Python Tutorial #14)
6 Python Exercise Problems for Beginners - from CodingBat (Python Tutorial #14)
CS Dojo
59 Google Coding Interview - Universal Value Tree Problem
Google Coding Interview - Universal Value Tree Problem
CS Dojo
60 Best laptops for programming? How to get a job at Google? - And other FAQ’s!
Best laptops for programming? How to get a job at Google? - And other FAQ’s!
CS Dojo

Related Reads

📰
The Minecraft anvil is a tree-cost optimization problem in disguise
Optimize tree costs in Minecraft using graph theory and algorithms, just like the anvil repair system
Dev.to · Mark
📰
KMP Algorithm (Knuth-Morris-Pratt): The Smart Way to Perform String Matching in O(N)
Learn the KMP algorithm for efficient string matching in O(N) time complexity and improve your coding skills
Dev.to · Jaspreet singh
📰
Every Backtracking Problem Is the Same Three Lines. I Just Couldn't See the Tree.
Master backtracking problems with a simple three-line approach to improve problem-solving skills in coding interviews and challenges
Dev.to · Alex Mateo
📰
DSA From Zero to Hero #3: Sliding Window (Fixed Size) Explained With a Java Example
Learn to solve subarray problems efficiently using the sliding window technique, a crucial skill for software engineers and data scientists
Medium · Programming
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →