Algorithms: Binary Search

HackerRank · Beginner ·⚡ Algorithms & Data Structures ·9y ago

Key Takeaways

The video covers the basics of the binary search algorithm, including its implementation in both recursive and iterative methods, and explains how it works on a sorted array to find a target element.

Full Transcript

hi I'm Gail lock McDow author of Kraken coding interview today we're going to cover binary search so binary search is a very intuitive algorithm and I'm going to show how intuitive It Is by giving an example you're a teacher and you're teaching a group of students a very large class of 300 students and you have their papers alphabetized out in front of you when a student Zack Peters comes up to get for get his paper back so you probably wouldn't go through the papers starting with Alex to an to Andrew and then to Bob and Brenda and Brandy and then to Chris and Christine and uh you probably wouldn't do it that way what you'd probably do is open the paper open the stack of papers to roughly halfway through the papers and compare it Zack Peters well that you open up halfway through and you see Michael matters there and you'd say Okay Zack Peters is after that name and then you take the second stack of papers and you'd treat it as its own little stack and you'd again say okay let me open up to its midpoint maybe we see Sarah well is Sarah before or after Zack Peters and then you just go and repeat this process over and over and over again until you find Zach's paper or until you find out Zach can't be in here and this is the basics of binary search so on an integer array it looks like this you take some element that you're looking for like 13 and you compare it to the midpoint and it has to be a sorted array for this to work it's very important you compare it to the midpoint 13 is less than this midpoint and so 13 if it's in the array at all it has to be on the left side and then You' repeat this process on the left side and say let me look at the midpoint of the left side it's 13 before and after that before after that and you just repeat that process until you either find 13 or you know that 13 can't be in it so how fast is this algorithm well let's imagine we start off with n elements so we have a search space of n elements in a single comparison just one we've cut our search space down to n/ two then with one more comparison we cut it down to n/4 and then and half again and half and half and half and half again so how many total operations in the very worst case will we have to run until we figure out if it contains an element or not well the total number of operations we'll have to do is determine by how many times can we divide n by two until we get down to just one so this is what log of n expresses or log base 2 of n expresses so and if you pause the video you can study that math for a second and see the relationship between those two things but this means that binary search is a log n problem let's look now at the implementation of binary search to implement binary search we can either implement it recursively or iteratively we'll do a cursive implementation first so I'm going to just copy and paste here some uh just straightforward code for the binary search call so this is a you know initial method that calls off to this binary search recursive method with the right parameters so we're going to start off initially with left being zero and right being the very right point so these are inclusive end points so first of all if things get kind of too big if left winds up bigger than right then we know we have an error we can't find it and we want to return true otherwise we want to pick the midpoint so left. right divided two that's going to be the midpoint and if we found the element if array of mid is actually this element we're looking for then we should return true otherwise if x is on the left side of mid then go search the left side uh so pass an array X and left will stay as is and the right point will mid will move to one next to the mid otherwise go search the right side so we want to call very similar method but now the left Point moves up to Mid + one and right stays as is okay so that's how the binary search recursive implementation looks so one little minor Pitfall is that some and some people like to be careful of is that left plus right can actually overflow with Java integers so if you'd like to avoid the integer overflow issue you can actually just do this instead and this will prevent the Overflow it's kind of up to up to you but this is one way of doing it okay so now that we've done the recursive implementation let's turn to the iterative implementation so what I'm going to do is I'm going to actually tweak this recursive implementation I'm going to copy paste it into a new function and I'm going to tweak it to make it iterative so I'm going to call this iterative and I no longer need parameters in here but what I'm going to do is I'm going to set so I'm going to show you how you can kind of tweak it so I'm going set left to be that right is going to start off at the rightmost position in the array so now I want to iterate as long I want to Loop through this as long as left and right are essentially in the correct positions so change this to a while loop all right and then if I exit here then I haven't found it okay so this looks correct and then here I don't want to actually recurse anymore what I want to do is essentially take these values here so left is going to stay as is and right is going to move to Mid minus one comment that out and I'll delete it shortly and then here rather than so left is going to stay or left is going to become mid + one and right is going to stay as is so that's how easy it is to tweak it from recursive to iterative so that's how we Implement binary search now remember that it can be implemented recursively or or itly and it can also be applied to other data like strings or something else but it must always operate on something that's sorted so now that you've seen the implementation of binary search why don't you try to do binary search on a new data type like a string good luck

Original Description

Learn the basics of binary search algorithm. This video is a part of HackerRank's Cracking The Coding Interview Tutorial with Gayle Laakmann McDowell. http://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview?utm_source=video&utm_medium=youtube&utm_campaign=ctci
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from HackerRank · HackerRank · 35 of 60

1 HackerRank for Professors
HackerRank for Professors
HackerRank
2 Why CareerCup's Gayle Laakmann McDowell Loves HackerRank [Testimonial]
Why CareerCup's Gayle Laakmann McDowell Loves HackerRank [Testimonial]
HackerRank
3 How to Leverage Data-Driven Insights to Improve Recruiting Results
How to Leverage Data-Driven Insights to Improve Recruiting Results
HackerRank
4 Hire Top Linux Talent and System Admins with SudoRank [Webinar]
Hire Top Linux Talent and System Admins with SudoRank [Webinar]
HackerRank
5 How Zenefits Hired 10 Engineers in 10 Days with HackerRank's CodeSprint
How Zenefits Hired 10 Engineers in 10 Days with HackerRank's CodeSprint
HackerRank
6 Hire the hottest SQL talent with DbRank from HackerRank [Tutorial]
Hire the hottest SQL talent with DbRank from HackerRank [Tutorial]
HackerRank
7 How to Use HackerRank's CodePair Tool [Tutorial]
How to Use HackerRank's CodePair Tool [Tutorial]
HackerRank
8 Find Linux Talent with SudoRank challenges [Tutorial]
Find Linux Talent with SudoRank challenges [Tutorial]
HackerRank
9 VMware's Mat Connot details his favorite new way to engage top programmers
VMware's Mat Connot details his favorite new way to engage top programmers
HackerRank
10 An Inside Look at Coinbase's Recruiting Strategy [webinar]
An Inside Look at Coinbase's Recruiting Strategy [webinar]
HackerRank
11 How Evernote Enhanced Their Tech Recruiting Process
How Evernote Enhanced Their Tech Recruiting Process
HackerRank
12 5 strategies for being a tech recruiting champion with HackerRank [Webinar]
5 strategies for being a tech recruiting champion with HackerRank [Webinar]
HackerRank
13 HackerRank Story - Lets make the world flat!
HackerRank Story - Lets make the world flat!
HackerRank
14 Data Structures: Hash Tables
Data Structures: Hash Tables
HackerRank
15 Data Structures: Anagram Problem Solution
Data Structures: Anagram Problem Solution
HackerRank
16 Algorithms: Solve 'Lonley Integer' Using Bit Manipulation
Algorithms: Solve 'Lonley Integer' Using Bit Manipulation
HackerRank
17 Big O Notation
Big O Notation
HackerRank
18 Algorithms: Graph Search, DFS and BFS
Algorithms: Graph Search, DFS and BFS
HackerRank
19 Algorithms: Bit Manipulation
Algorithms: Bit Manipulation
HackerRank
20 Data Structures: Solve 'Find the Running Median' Using Heaps
Data Structures: Solve 'Find the Running Median' Using Heaps
HackerRank
21 Data Structures: Heaps
Data Structures: Heaps
HackerRank
22 Algorithms: Memoization and Dynamic Programming
Algorithms: Memoization and Dynamic Programming
HackerRank
23 Algorithms: Sort An Array with Comparator
Algorithms: Sort An Array with Comparator
HackerRank
24 Algorithms: Solve 'Coin Change' Using Memoization and DP
Algorithms: Solve 'Coin Change' Using Memoization and DP
HackerRank
25 Data Structures: Solve 'Contacts' Using Tries
Data Structures: Solve 'Contacts' Using Tries
HackerRank
26 Data Structures: Tries
Data Structures: Tries
HackerRank
27 Algorithms: Bubble Sort
Algorithms: Bubble Sort
HackerRank
28 Algorithms: Merge Sort
Algorithms: Merge Sort
HackerRank
29 Algorithms: Quicksort
Algorithms: Quicksort
HackerRank
30 Data Structures: Binary Search Tree
Data Structures: Binary Search Tree
HackerRank
31 Data Structures: Trees
Data Structures: Trees
HackerRank
32 Algorithms: Solve 'Shortest Reach' Using BFS
Algorithms: Solve 'Shortest Reach' Using BFS
HackerRank
33 Algorithms: Solve 'Connected Cells' Using DFS
Algorithms: Solve 'Connected Cells' Using DFS
HackerRank
34 Algorithms: Solve 'Recursive Staircase' Using Recursion
Algorithms: Solve 'Recursive Staircase' Using Recursion
HackerRank
Algorithms: Binary Search
Algorithms: Binary Search
HackerRank
36 Algorithms: Solve 'Ice Cream Parlor' Using Binary Search
Algorithms: Solve 'Ice Cream Parlor' Using Binary Search
HackerRank
37 Data Structures: Linked Lists
Data Structures: Linked Lists
HackerRank
38 Data Structures: Cycles in a Linked List
Data Structures: Cycles in a Linked List
HackerRank
39 Data Structures: Stacks and Queues
Data Structures: Stacks and Queues
HackerRank
40 Data Structures: Queue With Two Stacks
Data Structures: Queue With Two Stacks
HackerRank
41 Data Structures: Balanced Parentheses in Expression
Data Structures: Balanced Parentheses in Expression
HackerRank
42 Algorithms: Recursion
Algorithms: Recursion
HackerRank
43 How to Hire for Your Startup [Collision Panel Video]
How to Hire for Your Startup [Collision Panel Video]
HackerRank
44 HackerRank main() San Francisco | November 8, 2018
HackerRank main() San Francisco | November 8, 2018
HackerRank
45 The Enterprise Playbook for Technical Hiring
The Enterprise Playbook for Technical Hiring
HackerRank
46 Remote Hiring Colloquy with EY's Dipika Kapadia & BigBasket's Rupesh Kumar
Remote Hiring Colloquy with EY's Dipika Kapadia & BigBasket's Rupesh Kumar
HackerRank
47 Remote Hiring Colloquy with Hackerrank's Hari K, Akamai's Neha Akhouri & Infosys's Rafee Tarafdar
Remote Hiring Colloquy with Hackerrank's Hari K, Akamai's Neha Akhouri & Infosys's Rafee Tarafdar
HackerRank
48 Building a Culture for Developer Innovation
Building a Culture for Developer Innovation
HackerRank
49 Developer Trends in 2020 and Beyond
Developer Trends in 2020 and Beyond
HackerRank
50 HackerRank's Livestream: Accelerating Developer Innovation at PhonePe
HackerRank's Livestream: Accelerating Developer Innovation at PhonePe
HackerRank
51 Aadil Bandukwala converses with Rahul Chari about HackerRank's upcoming livestream
Aadil Bandukwala converses with Rahul Chari about HackerRank's upcoming livestream
HackerRank
52 Accelerating Developer Innovation at PhonePe with Rahul Chari
Accelerating Developer Innovation at PhonePe with Rahul Chari
HackerRank
53 The Future of Work for Developers
The Future of Work for Developers
HackerRank
54 Scaling AI from Proof of Concept to Production
Scaling AI from Proof of Concept to Production
HackerRank
55 The Secret Sauce to getting hired in Myntra’s Tech Team
The Secret Sauce to getting hired in Myntra’s Tech Team
HackerRank
56 Reimagining Money with Paypal
Reimagining Money with Paypal
HackerRank
57 Engineering Predictions for 2021 and Beyond! 🎬
Engineering Predictions for 2021 and Beyond! 🎬
HackerRank
58 Future-forward Tech & Careers with BNY Mellon
Future-forward Tech & Careers with BNY Mellon
HackerRank
59 How Atlassian Approaches Diversity and Inclusion with Balance & Belonging
How Atlassian Approaches Diversity and Inclusion with Balance & Belonging
HackerRank
60 Connecting Global Tech Ecosystems: Andela Shines a Light on Africa’s Developer Talent
Connecting Global Tech Ecosystems: Andela Shines a Light on Africa’s Developer Talent
HackerRank

The binary search algorithm is a fast and efficient way to find an element in a sorted array. It works by repeatedly dividing the search space in half until the target element is found. The algorithm can be implemented recursively or iteratively.

Key Takeaways
  1. Start with a sorted array and a target element
  2. Find the midpoint of the array
  3. Compare the target element to the midpoint
  4. If the target element is less than the midpoint, repeat the process on the left half of the array
  5. If the target element is greater than the midpoint, repeat the process on the right half of the array
  6. Continue this process until the target element is found or the search space is empty
💡 The binary search algorithm has a time complexity of O(log n), making it much faster than linear search for large datasets.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →