Binary Search tutorial (C++ and Python)

แชร์
ฝัง
  • เผยแพร่เมื่อ 18 ม.ค. 2025
  • This is the most comprehensive lecture on the binary search. Find the target value, or the first value satisfying some condition, or approximate sqrt(x) up to some precision. Watch this lecture if you practice for competitive programming or for coding interviews. See the pinned comment for links and my implementation. Consider turning captions on and setting the speed to x1.25.
    Please give me suggestions about the format of a lecture or about topics for future lectures.
    Frequently Asked Questions: github.com/Err...
    Github repository: github.com/Err...
    Facebook: / errichto
    Twitter: / errichto
    Competitive Programming Discord: discordapp.com...
    TH-cam channel 1: / errichto (mainly short videos)
    TH-cam channel 2: / errichto2 (streams)
    I’m Kamil Dębowski, better known as Errichto. I compete in and organize programming competitions. I make educational streams on TH-cam and Twitch. I'm a finalist of ACM-ICPC, Topcoder Open, Facebook Hacker Cup and Google Code Jam. I got a second place in Google Code Jam 2018. I am/was nutella in Codeforces and target in Topcoder.
    Watch me if you want to practice for coding interviews, competitive programming or just algorithms in general. I share my thought process, explain everything, and mention similar problems and techniques/algorithms.

ความคิดเห็น • 329

  • @Errichto
    @Errichto  5 ปีที่แล้ว +297

    I recommend solving binary search problems on Leetcode (leetcode.com/explore/learn/card/binary-search/). Don't read their templates though, they aren't perfect.
    Start with easy problems: leetcode.com/explore/learn/card/binary-search/125/template-i/951/, leetcode.com/explore/learn/card/binary-search/126/template-ii/947/, leetcode.com/explore/learn/card/binary-search/126/template-ii/949/.
    You can find C++ and Python codes to some problems in my GitHub repo, github.com/Errichto/youtube/tree/master/lectures/binary-search.
    Note that some problems aren't same with what I talked about during a lecture. For example, Find Peak Element in Leetcode seems harder because the function can have multiple peaks.
    Huge thanks to Reddy for making captions!

    • @earth20010
      @earth20010 5 ปีที่แล้ว

      Thanks!

    • @swagatochatterjee7104
      @swagatochatterjee7104 5 ปีที่แล้ว

      I was trying to apply that ans = mid template for finding the minimum element in a sorted array. Was I doing something wrong?

    • @jdhp3696
      @jdhp3696 4 ปีที่แล้ว

      Thank you for the wonderful video. It really help me understand the algorithm better. It will be really great if you can do more videos like this where you go over other data structures and algorithms that are most used especially in interviews.

    • @Sehyo
      @Sehyo 4 ปีที่แล้ว

      4:20 Since (L+R)/2 would overflow, shouldn't (L/2) + (R/2) work though?

    • @roufshaik3530
      @roufshaik3530 4 ปีที่แล้ว

      what would be the eps value in sqrt() function?

  • @naughtyrishan
    @naughtyrishan 5 ปีที่แล้ว +275

    Thanks so much for such videos. A lot of people struggle badly to be good at competitive programming. You make their life easy. Thanks again.

    • @musicfan1695
      @musicfan1695 4 ปีที่แล้ว +13

      adding to that, you are a very humble person as well.

  • @kshitijpatil2019
    @kshitijpatil2019 3 ปีที่แล้ว +55

    The most important lesson I learned from this video, don't bother updating low/high conditionally, stick with only one binary search template (for 99% of the cases), and use a variable instead to store pivot position as per your condition. It makes every binary problem 10x easier for me.

  • @sarveshdubey9347
    @sarveshdubey9347 5 ปีที่แล้ว +110

    Hi, Sarvesh from India
    Please keep making such Conceptual videos.

  • @sauravpaul4131
    @sauravpaul4131 5 ปีที่แล้ว +95

    Best lecture on binary search implementation, thanks Errichto.

  • @rajbapat5607
    @rajbapat5607 5 ปีที่แล้ว +42

    Great video! I can finally write binary search without hesitating or wasting time debugging a +1/-1 issue.

  • @medievalogic
    @medievalogic 3 ปีที่แล้ว +5

    I finally understood the idea of "getting a better answer". Most binary implementation on the Internet look like hacky, with people incrementing or decrementing the mid by one to get a desired answer. Thanks a bunch.

  • @nijikatherock
    @nijikatherock 3 ปีที่แล้ว +3

    that observation where we can generalize the problem to a prefix of Falses and a suffix of Trues was mindblowing. thank you so much!

  • @dharmanshah1239
    @dharmanshah1239 5 ปีที่แล้ว +50

    Thanks errichto for the well prepared material and thanks Reddy for captions!!

  • @TheGanesamurthi
    @TheGanesamurthi 5 ปีที่แล้ว +7

    The best half hour that I spent in entire 2020

  • @AniketKumar-xg3ky
    @AniketKumar-xg3ky 5 ปีที่แล้ว +4

    It is so far the best binary search video I have watched on TH-cam,Thank You very much....

  • @dcodernz
    @dcodernz 5 ปีที่แล้ว +7

    Thanks Errichto! This was by far the best explanation I've seen/heard of binary search! I thought I had understood it before but this has deepened my understanding profoundly. The length is also good. I think it would help us all a lot of you did more videos like this to really get a deep understanding of algorithms.

  • @shubhamagrawal2407
    @shubhamagrawal2407 5 ปีที่แล้ว +6

    Thanks Errichto, after watching this video now I have a better understanding of binary search and its applications.

  • @rohan8arora
    @rohan8arora 5 ปีที่แล้ว +2

    All the things I learnt over weeks in a small 30 min video, thanks errichto!

  • @franceshe1350
    @franceshe1350 5 ปีที่แล้ว +7

    Thank you! This is one of the best algorithm video with clarity and great explanations I saw so far! I learned so much, plz keep update these algorithm videos, maybe the more general ones that people used everyday. I think that might have a bigger impact for the general public :)

  • @srikanthkoraveni8210
    @srikanthkoraveni8210 5 ปีที่แล้ว +2

    Thank you very much. Please continue to make videos covering the fundamentals. Loved the clear, concise and comprehensive presentation.

  • @codepractices7
    @codepractices7 5 ปีที่แล้ว +2

    Thank you so much errichto! Please continue to make such comprehensive tutorials!!

  • @SumitBadsara
    @SumitBadsara 5 ปีที่แล้ว +8

    This is the actual binary search! Not just (L+R)/2 . Thanks for these examples. Keep making such videos. Love from India🇮🇳.

    • @devendrasingh4776
      @devendrasingh4776 4 ปีที่แล้ว +3

      Well it is correct but will give int overflow . So it better to be on safer side . Thats it .

    • @SumitBadsara
      @SumitBadsara 4 ปีที่แล้ว

      @@devendrasingh4776 Bruh! That was just an example 😂. I meant he is not teaching the concept. He is teaching practical implementation. Like after this, some people might see binary search with a totally different perspective.

    • @devendrasingh4776
      @devendrasingh4776 4 ปีที่แล้ว +2

      @@SumitBadsara exactly . I am that guy who has changed perspective. Now i think like more of finding that condition rather than blindly dividing into half. All thanks to this guy.. 😊

  • @Nyquiiist
    @Nyquiiist 3 ปีที่แล้ว +1

    Hands down the best explanation I've come across on BS yet. Looking at it from a a PoV of prefixes and suffixes was really eye opening, and has made solving some problems suuper easy. Thank you!!!

  • @prabhatsharma284
    @prabhatsharma284 5 ปีที่แล้ว +1

    You cannot find a lecture on binary search better than this!

  • @anweshbhattacharya8017
    @anweshbhattacharya8017 4 ปีที่แล้ว +2

    Thank you Errichto for the top-notch pedagogical content. Your techniques in this video helped me in one particular question in a technical interview for Amazon. I didn't receive the final offer, however it was a great experience thanks to you!

  • @pradyundevarakonda6849
    @pradyundevarakonda6849 5 หลายเดือนก่อน

    This channel is a goldmine!
    Glad I found this before getting my cs major

  • @BGivo
    @BGivo 5 ปีที่แล้ว +2

    That was great, thank you. More videos like this, where you introduce a concept, and then provide related examples, would be amazing.

  • @dominikdabrowski7082
    @dominikdabrowski7082 4 ปีที่แล้ว

    I was really struggling with binary search, but your video made all the difference, thanks Kamil!

  • @shroud3354
    @shroud3354 5 ปีที่แล้ว +7

    World class video must watch everyone👍

  • @gupta_samarth
    @gupta_samarth 5 ปีที่แล้ว +5

    Really awesome lecture. Thanks a lot for all the time you put into preparing this stuff. All those hours of BPS surely do pay off. Can't wait to learn more things from you.

  • @kpopisthebestful
    @kpopisthebestful 5 ปีที่แล้ว +10

    You should do more of these lectures, like sorting algos and data structures

  • @de_naenae
    @de_naenae 3 ปีที่แล้ว +1

    Very intuitive explanations. I have never come across keeping an "ans" variable but it makes so much sense. Much easier to understand than other solutions!

  • @adityarai8963
    @adityarai8963 2 ปีที่แล้ว

    This is by far the best video for binary search. Kudos to your amazing work, Errichto!

  • @matiyasyohannes5502
    @matiyasyohannes5502 2 ปีที่แล้ว

    This is the best lecture on binary search. Thank you Errichto

  • @iamtrash288
    @iamtrash288 4 ปีที่แล้ว +1

    Thank you for the comprehensive explanation of binary search! I really didn't know it was so powerful before!

  • @sanddevelopers
    @sanddevelopers 5 ปีที่แล้ว +10

    Thanks a lot for the clear explanation

  • @darshantawte7435
    @darshantawte7435 4 ปีที่แล้ว

    Best video on binary search I have seen till now

  • @alexneagu4466
    @alexneagu4466 5 ปีที่แล้ว +1

    Congrats, Kamil, for a great video! With every video i learn more and more. Please make more videos like this, where you explain other popular algorithms. (segment trees, graph theory, string algoritms like KMP, etc.)

  • @jannoszczyk5132
    @jannoszczyk5132 5 ปีที่แล้ว

    Właśnie znalazłem twój kanał po obejrzeniu twojego wywiadu z Joma.
    Bardzo dokładnie i prosto wszystko tłumaczysz. Zdecydowanie najlepszy kanał z algorytmami jaki dotychczas widziałem!! Keep it up!

  • @lpdc9767
    @lpdc9767 5 ปีที่แล้ว +1

    Thanks so much for the clear and concise material! I hope you keep making these.

  • @kaushaldawra3527
    @kaushaldawra3527 3 ปีที่แล้ว

    I feel this is the best binary search visualisation and strategy explanation because one thing is correct, it is a simple algorithm but at the same time it is very easy to write a buggy code for it.
    Thank you

  • @psibarpsi
    @psibarpsi 2 ปีที่แล้ว +1

    This was great. Helped me learn a lot. I would be looking forward to more such sessions.

  • @davidjiang7929
    @davidjiang7929 4 ปีที่แล้ว

    Thanks for sharing! Your explanations are clear and concise. Also congrats on recent win!

  • @sameerbhatti363
    @sameerbhatti363 3 ปีที่แล้ว

    Great video! You helped better understand binary search, but more importantly, its implications. You are a great teacher. Thank you.

  • @SuperArjun11
    @SuperArjun11 5 ปีที่แล้ว +22

    This was great. Will you be covering data structures/algorithms not typically found in undergrad books? Square root decomposition and seg trees for example.

    • @ajr1791ze
      @ajr1791ze 5 ปีที่แล้ว +4

      yes, i also say so.

    • @Errichto
      @Errichto  5 ปีที่แล้ว +23

      Yes, I plan both sqrt deco and seg trees :) More video ideas here: github.com/Errichto/youtube/wiki/Video-ideas

    • @kushagrasahni9708
      @kushagrasahni9708 4 ปีที่แล้ว +2

      @@Errichto Please make a video on segment and fenwick trees.

  • @literallynoone2093
    @literallynoone2093 2 ปีที่แล้ว

    Thanks a lot man! I was struggling to get a hold of all the variations. You made it so simple!

  • @rehanakhter4813
    @rehanakhter4813 3 ปีที่แล้ว

    Best explaination of binary search in youtube. Thanks a lot!

  • @Woef718
    @Woef718 3 ปีที่แล้ว

    This year I was studying mathematics on university Leiden and I dont know but my interest to learn mathematics declined so much just by attending school. A month ago I dropped out and found your videos and now I fell in love with competitive programming. Thank you so much!

  • @kairatopa9564
    @kairatopa9564 4 ปีที่แล้ว +1

    Thanks man u made my interview preparation much easier

  • @himanshulal4454
    @himanshulal4454 ปีที่แล้ว

    Excellent way to cover Binary Search using a systematic way.. Thanks a lot

  • @priyanandshukla8388
    @priyanandshukla8388 4 ปีที่แล้ว

    One of the best lectures on binary search

  • @icenberg5908
    @icenberg5908 4 ปีที่แล้ว

    Thanks errichto for your efforts and clear presentation.

  • @nayanchudasama2014
    @nayanchudasama2014 3 ปีที่แล้ว

    What a great lecture, now binary search is Perfectly clear.
    Thanks a lot sir

  • @raselhasan2433
    @raselhasan2433 3 ปีที่แล้ว

    I loved your lecture, as a teacher/trainer of coding, you are best. Thanks man.

  • @geekySRM
    @geekySRM 3 ปีที่แล้ว

    This is so awesome! Thank you so much @Errichto!

  • @KarthikKarthik-el5hh
    @KarthikKarthik-el5hh 2 ปีที่แล้ว

    thank you so much errichto, ur explanation was awesome
    now i understand binary search better

  • @mehedihasanjoy8726
    @mehedihasanjoy8726 5 ปีที่แล้ว +34

    Pls do a leture on basic greedy and DP

    • @Errichto
      @Errichto  5 ปีที่แล้ว +29

      I'm planning a lecture on dp, actually. It should be out soon.

  • @koocheukkeijacky9704
    @koocheukkeijacky9704 5 ปีที่แล้ว +2

    Really appreciate of your videos !! very clear explanation

    • @Errichto
      @Errichto  5 ปีที่แล้ว

      Thank you!

  • @wizardOfRobots
    @wizardOfRobots 3 ปีที่แล้ว

    Thanks for the great lecture! Instead of a template, you gave me a proper way to think of the algorithm.

  • @codexhammered007
    @codexhammered007 3 ปีที่แล้ว

    In the sorted rotated array variation. It's safe to say that assume false when element at mid is greater than "or equal to" the last element. Only greater than would fail for the case when the smallest number is repeated. Eg. 6, 7, 9, 9, 15, 19, 2, 2, 3

  • @namanbudhiraja6756
    @namanbudhiraja6756 4 ปีที่แล้ว

    Hey Errichto, after watching this video , i have solved my all doubts related to binary search.Thanks for the amazing explanation.Love from India

  • @anands9407
    @anands9407 4 ปีที่แล้ว +4

    Usually really smart people like u are not known for their great teaching skills...
    U really changed that!

  • @__-to3hq
    @__-to3hq 5 ปีที่แล้ว +11

    "The study from 1988 showed that only one in four textbooks has a correct implementation..."

  • @Rich65501
    @Rich65501 5 ปีที่แล้ว

    Excellent -- thanks for the correct way to calculate the midpoint in binary search.

  • @blu5037
    @blu5037 5 ปีที่แล้ว +1

    Wow, super great video. Thanks for making this errichto.

  • @shroudyboi5673
    @shroudyboi5673 4 ปีที่แล้ว

    Wow he has explained the concept of discrete binary search beautifully. The topcoder tutorial was good but this video covers the topic really well

  • @amritbhardwaj99
    @amritbhardwaj99 4 ปีที่แล้ว

    This is a MUST watch vid on binary search!!

  • @rahulsbhatt
    @rahulsbhatt 4 ปีที่แล้ว

    This is legit the best binary search video anyone has made 👏

  • @doejohn5637
    @doejohn5637 ปีที่แล้ว

    what a brilliant idea of thinking binary search problems as elements of search space being T or F !

  • @abhishekgaurgaur
    @abhishekgaurgaur 3 ปีที่แล้ว

    Thank you very much Errichto, really appreciate it. ❤️

  • @Sean-jv6bd
    @Sean-jv6bd 4 ปีที่แล้ว

    Hi Errichto this is an amazing lecture! Thank you so much and please keep up the great work!

  • @cccctainvista
    @cccctainvista 4 ปีที่แล้ว

    Great video, love it, you are very good at making complex problems seem very simple!

  • @abhishekdhok5245
    @abhishekdhok5245 3 ปีที่แล้ว +1

    CP God for a reason.. Love your efforts. Love from India

  • @thuanvo9283
    @thuanvo9283 3 ปีที่แล้ว

    Your ways so easy to understand. thank you Eric so much!!!

  • @yawningcats
    @yawningcats 3 ปีที่แล้ว

    it was very good, I thought I new binary search but after watching this video I found out much more. It was really helpful. Thank you

  • @youssefbou1503
    @youssefbou1503 5 ปีที่แล้ว +2

    Great video! Which topics do you plan to do next ? and will you focus more on cp or interview preparation?

    • @Errichto
      @Errichto  5 ปีที่แล้ว

      You can read my video ideas in my GitHub wiki: github.com/Errichto/youtube/wiki/Video-ideas
      I want to mix cp and interview prep.

  • @becomingbesthackerprogramm4644
    @becomingbesthackerprogramm4644 2 ปีที่แล้ว

    Lovely classic lecture , mesmerized by explanations , thanks alot ❤️

  • @saitama-fv6my
    @saitama-fv6my 2 ปีที่แล้ว

    I watched your video and I got explained my topic what I wanted for. thank you so much sir 🙏

  • @SushantKumar-iy4is
    @SushantKumar-iy4is 4 ปีที่แล้ว

    Well explained, Errichto. Clean and Simple.

  • @omanshsharma6796
    @omanshsharma6796 2 ปีที่แล้ว

    thanks a lot enrichto!! beautifully explained!!

  • @avisekshaw4748
    @avisekshaw4748 4 ปีที่แล้ว

    Great work bro. Thank you for uploading such a great content.

  • @chandup832
    @chandup832 3 หลายเดือนก่อน

    I have lost from rotated array, till then it was awesome!

  • @darshpatel8385
    @darshpatel8385 4 ปีที่แล้ว

    This video was really helpful to me. Thanks for making such good content.

  • @pradiptarakshit35
    @pradiptarakshit35 4 ปีที่แล้ว +5

    Please, do a lecture on Graph Algorithms. Also, thanks for this video.

  • @lovleshbhatt7797
    @lovleshbhatt7797 4 ปีที่แล้ว +1

    need second part of this lecture as soon as possible , its a humble request from the fan side

  • @ivanleon6164
    @ivanleon6164 3 ปีที่แล้ว

    greetings from Mexico! those videos are really cool, thanks for all the effort put on those.

  • @133839297
    @133839297 3 ปีที่แล้ว

    Let's keep it binary with 2 words: PURE GOLD!

  • @abdurrahaman388
    @abdurrahaman388 4 ปีที่แล้ว

    Most informative binary search tutorial ❤️

  • @smitaagarwal8819
    @smitaagarwal8819 23 วันที่ผ่านมา

    Covers a lot of important observation and pattern in binary search.

  • @omti
    @omti 5 ปีที่แล้ว +2

    Very cool content! Thank you!
    Waiting for more videos...

  • @rajansaharaju1427
    @rajansaharaju1427 5 ปีที่แล้ว +13

    It's really safe zone but didn't think before. Thanks. L + (R-L)/2 = (2L + R - L) /2 = (L + R)/2

    • @GreatKrish1
      @GreatKrish1 9 หลายเดือนก่อน

      I think 2L and L+R will overflow

    • @zafirhasananogh2421
      @zafirhasananogh2421 2 หลายเดือนก่อน

      @@GreatKrish1 they were probably demonstrating how L + (R-L)/2 and (L + R)/2 is the same but does not overflow

    • @GreatKrish1
      @GreatKrish1 หลายเดือนก่อน

      @@zafirhasananogh2421 Yeah that's what I wrote

  • @rohanvtk
    @rohanvtk 4 ปีที่แล้ว +1

    2:46 the correct formula and the reason why :)

  • @areebwadood6273
    @areebwadood6273 5 ปีที่แล้ว +1

    Great learned some new applications of binary search

  • @barakode414
    @barakode414 4 ปีที่แล้ว

    Thank you very much. It's easy after watching your video.

  • @adityakajale4403
    @adityakajale4403 3 ปีที่แล้ว

    Best lecture on binary search

  • @laskdkmgful
    @laskdkmgful 5 ปีที่แล้ว

    Best lecturer I have seen. Thanks!

  • @mindpower05
    @mindpower05 5 ปีที่แล้ว +6

    Hi Errichto, Thanks for such an amazing video. Can you please guide on how you write such clean and simple code? I have seen your code and ecnerwala's code in CF contests and they seems very crisp, precise and to the point, generally less then 50 lines. How to improve our thinking and coding to write such neat and to the point code?
    Thanks in advance :)

  • @primerevan8403
    @primerevan8403 3 ปีที่แล้ว

    Just clicked before thinking let's watch something might come up .

  • @murahat98
    @murahat98 3 ปีที่แล้ว +2

    Everyone else: Use (l+r)/2 to find the middle element. No problem at all.
    Errichto: Never use this formula xD

  • @yamisekai
    @yamisekai 4 ปีที่แล้ว

    Thank you for sharing your knowledge, great video!

  • @BotDesigner
    @BotDesigner ปีที่แล้ว

    Thank you so much for this, I have a question for you @Errichto, is this implementation the one that you still using nowadays?

  • @lazizaakramova8602
    @lazizaakramova8602 ปีที่แล้ว

    Thank you very much! You are incredible!

  • @krishneshchaurasia3839
    @krishneshchaurasia3839 ปีที่แล้ว

    this is good stuff, now I know why people call you god of cp... orz

  • @akashdalvi5369
    @akashdalvi5369 2 ปีที่แล้ว

    Thanks man, awesome perspective