Binary Search - Leetcode 704 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 11 ก.ย. 2024

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

  • @tanmay______
    @tanmay______ 2 ปีที่แล้ว +161

    Thanks for mentioning the integer overflow problem!

    • @CST1992
      @CST1992 6 หลายเดือนก่อน +4

      This kind of attention to detail is what separates great from just good.

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

    It's fascinating how beginner friendly this explanation was despite how professional you are, thank you

  • @numberonep5404
    @numberonep5404 2 ปีที่แล้ว +44

    Always good to practice the basics! I am just happy to recieve a notification from neetcode :d

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

      gotta do the classics sometimes

  • @h.t.4846
    @h.t.4846 2 ปีที่แล้ว +17

    can't thank you enough for ur tutorials! it's for sure in depth and easy to digest!

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

    Great video! It helped me with this!
    For those coding in JavaScript, be sure to make the middle variable: let middle = Math.round((left + right) / 2); Otherwise the value will be 2.5 instead of 3.

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

      Thank You!

  • @bartekbinda6978
    @bartekbinda6978 7 หลายเดือนก่อน +2

    I’ve actually always coded the binary search using the distance approach and never thought about your original approach to determine the mid point, thanks

  • @staffeng
    @staffeng 2 ปีที่แล้ว +8

    There's also a version of binary search where we would need to return where the element's index would be had it been there in the collection. And this is exactly how Collections.binarySearch() and Arrays.binarySearch() is implemented in Java. For example, you have a collection [1,2,3,4,5] and if you search for 0, then Collections.binarySearch() will return -1 but that's because 0 would have been at the first place at index 0 so it's that index 0 in negative form minus 1 which is equal to -1. To take another example, let's say you are searching the same collection for element 6, then Collections.binarySearch() will return -6 (-5 - 1).

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

    The best explain to beginner including the integer overflow I ever seen

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

    the recursive approach.
    if len(nums) == 0:
    return -1
    mid = (len(nums)) // 2
    if nums[mid] == target:
    return mid
    elif nums[mid] > target:
    return self.search(nums[:mid], target)
    else:
    result = self.search(nums[mid+1:], target)
    startIdx = mid + 1
    if result != -1:
    return startIdx + result
    else:
    return -1

  • @Ashley-mc5bi
    @Ashley-mc5bi 3 หลายเดือนก่อน +1

    My data structures professor secretly gets his entire lectures from your videos! Except you explain things much better lol. Thanks for all your help!

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

    Hi,
    Is there a pattern or a rule when choosing whether l

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

      I used l < r, but you have to check in the end when l == r, whether nums[l] or nums[r] == target
      l, r = 0, len(nums) - 1
      while l < r:
      m = (l + r) // 2
      if nums[m] == target:
      return m
      elif nums[m] < target:
      l = m + 1
      else:
      r = m - 1
      return l if nums[l] == target else -1

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

      I am guessing it depends on if you need to do something with the l=r condition, also for binary search, if the element has just one element, condition l

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

    that log n breakdown just helped me for sure !

  • @free-palestine000
    @free-palestine000 2 ปีที่แล้ว +9

    Do you have any advice on how to remember the fundamentals on a topic while you're working on other topics? I'm struggling to retain details from trees while im working on strings problems for example

    • @cc-to2jn
      @cc-to2jn 2 ปีที่แล้ว +15

      i would recc u do them in pattern order rather than randomly. This will help u truly understand the pattern and retain it.

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

      Grokking the coding interview is the answer you are looking for

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

      Review old solutions or topics you've done every other day.

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

      Use Anki to make flash cards. It’ll drill you every day using Spaced Repetition.

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

      @@scvkurt03 how would the problems/solutions translate to cards?

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

    Lol it's so hilarious that the last way you showed it's the one I did.
    Cause I was like surely it has to be simpler but I guess not 😂
    Took me a few tries to come up with it

  • @TheRailJunction
    @TheRailJunction 7 หลายเดือนก่อน +1

    TIL how we get log n complexity..

  • @chessingh
    @chessingh 2 ปีที่แล้ว +6

    Ah, neetcode doing the daily leetcode challenge 🥺🏆

  • @nur_6ek
    @nur_6ek 5 หลายเดือนก่อน +1

    you are legend bro😄

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

    Thanks for the video! I think it helps to mention the // syntax is a floor division, I have been implementing unnecessary checks on whether the array length is odd or even🥲

    • @ericdwkim
      @ericdwkim 10 หลายเดือนก่อน +2

      this comment cleared that up for me, thanks!

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

    I've always implemented the binary search using the distance method. I guess thats how they teach in all good algorithms course. But never knew the reason why

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

    Thank you for the video! Is there a way to do this with recursion??? Thanks!

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

    but you also have to add something for that solution of overflow problem, Because when the array have only one element, right would be negative in te while loop, they've been tricky these days

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

    Thank you, your explanation is amazing

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

    Hello Sir i am a big fan......I have a very important request....... Could you please make solution playlist of Striver's SDE Sheet. Its will be very beneficial for us students

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

    OMG thank you very much for your channel!

  • @Emorinken
    @Emorinken 3 วันที่ผ่านมา

    Thank you very much

  • @a.rohimsama7222
    @a.rohimsama7222 5 หลายเดือนก่อน

    Thank you. love it!

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

    In leetcode,I tried it and got wrong answer for
    nums = [4,5,6,7,0,1,2] , target = 0.output is -1 but expected is 4.Can u please help me?

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

    Can you explain, why it should be
    l=mid+1 or r=mid-1 not l=mid or r=mid

    • @VedantaNayak
      @VedantaNayak 2 ปีที่แล้ว +14

      Since we know mid is not the target, it will be redundant to include it in the next window.

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

    Thanks, neetcode.

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

    Thank you!

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

    that was great!

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

    Thank you sir

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

    For the overflow couldnt you also do (L // 2) + (R//2)

    • @iancampbell8420
      @iancampbell8420 26 วันที่ผ่านมา

      You can but it’s more efficient to do L + (R-L) // 2
      And usually these little details don’t particularly matter but since it’s an overflow problem, the numbers you’re working with are so large that those little intricacies matter a lot. They can change a program from usable to destructive.

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

    How can the list be added in the program????

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

    What confuses me is what happens in an array with a single value and the target is LESS than the value contained in the array. ie. Array = [1], Target = 0.
    Code Variable Theoretical Printout.
    L = 0, R=0, M=0
    Target is less than value at M, so R=m-1 and M=-1
    L=0 R=-1 M=-1
    Target is STILL less than value at M, so R=M-1, so R=-2 and M=-1??
    Value at M can never be reached, as M will never get smaller than -1????
    Neetcode, bless me with your knowledge of edgecases

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

      The while condition is L

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

      @@CoolerJ0k3r What if the Target is inside the left or right pointer itself? [-1,0,3,5,9,12] target 5. I changed the target to 5 in the given test case, the solution works fine, but how? Which line is handling that?

    • @juandager5220
      @juandager5220 2 หลายเดือนก่อน +1

      You are confusing values with index.
      Target is the actual number you are looking for.
      Middle is the current index of what you are searching for.
      So when M=0, you are checking for the value of the number at the index 0 of nums. Same with left and right: they are the minimum and maximum index.
      Makes sense?

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

      ​@@ikthedarchowdhury8947If the target is at an extreme, either on the left or right, the while loop will keep running until left == Right== middle.
      How do you search for words in a physical thesaurus or dictionary?
      What happens if you are searching for the first or last word in the entire dictionary?
      Zzzzzzzuly? Hope this helps!

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

      @@juandager5220 oh thx 🙏 that helped

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

    can we make the variable names more explanatory?

  • @darKnight_-_
    @darKnight_-_ 11 หลายเดือนก่อน

    running it with m=l+r//2 doesnt work anymore you have to use m=l+l-r//2 only, otherwise it gives a time limit exceeded error

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

      (l+r)//2 works just fine. Mind the brackets. In your m=l+l-r//2 you're really doing m=2*l - r//2, which works here, but is probably not what you intended to do.

    • @darKnight_-_
      @darKnight_-_ 10 หลายเดือนก่อน

      m=l+(r-l)//2 sorry@@eteran23

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

    Why we can't just make left or right equal to middle without increasing or decreasing mid value? I know that's more efficient but don't understand why search doesn't work without modifying mid value

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

      Left and right limit the section of nums where the possible solution is. And middle is the current index that you are comparing to the target.
      If middle is not the target, you need to adjust the new size by updating left OR right. Basically, discarding the upper or lower half. And then check again the new middle.
      The easiest real life example is how you search a dictionary. Grab a physical thesaurus and search for a word... That's binary search!
      Does that answer your question?

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

    "l, r=0, len(nums)-1 " can you explain this one ? i guess l=0 , r=0 but len(nums) -1 == ? its not like this r= len(nums) -1 , am i right ? Thank you

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

      nope it means l=0 and r=len(nums)-1 -> which means length of nums array - 1 so that we get last index of nums array and -1 because the index of array start from 0. hope it helps

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

      In Python, you can declare variables like this:
      Variable1, Variable2 = Value1, Value2
      So:
      L, R = 0, lens(nums) -1
      Is the same as:
      L=0
      R=lens(nums) - 1
      Does that answer your question?

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

    understood

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

    nice

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

    First :o

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

    this solution gives the wrong answer for me
    Target = 0
    [-5, 0, .....]
    last iteration, L=0, R=1,
    Midpoint: (0+1)//2 = 0
    since target >nums[midpoint], L = Midpoint +1 = 0 + 1 = 1
    now L has become greater than R, and the program returns false.

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

    👑you dropped this

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

    Anyone else think the l was a 1 and get really confused for a second?

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

      In which line of code? What timestamp?
      Some solutions:
      1. Write full words for variables: left, right
      2. Notice how the IDE has different colors for variables and numbers. L is white, 1 is purple.
      3. Practice more. And you'll gain intuition.

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

    for the (r+l)//2 problem you can easily do r//2 + l//2 because maths

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

      Not so. Remember, // is floor-division not float-division. Sometimes they're equal, but not always. E.g. (3+5)//2 = 4 while 3//2 + 5//2 = 1 + 2 = 3

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

    Beautiful!

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

    #completedbyaditi2206

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

    thank you sir