Search Insert Position - Binary Search - Leetcode 35 - Python

Sdílet
Vložit
  • čas přidán 7. 09. 2024

Komentáře • 69

  • @NeetCode
    @NeetCode  Před 3 lety +4

    💡 BINARY SEARCH PLAYLIST: czcams.com/video/U8XENwh8Oy8/video.html

  • @luckychitundu1070
    @luckychitundu1070 Před 2 lety +15

    Nice One! I came here to find out why we are returning left. Thanks brother.

    • @zhan1447
      @zhan1447 Před 2 lety +1

      Same here. I am a little confused why we are returning left in the end?

    • @hasibqureshi6409
      @hasibqureshi6409 Před rokem

      Same here

  • @alphabee8171
    @alphabee8171 Před 2 lety +5

    unlike others you had a clear understanding why to use binary search.

  • @CS_n00b
    @CS_n00b Před 2 lety +9

    that breathing at the end freaked me out lol

    • @NeetCode
      @NeetCode  Před 2 lety +5

      Lol damn I dont know how that was left in, it sounds like it was looping a few times

  • @ernie2111
    @ernie2111 Před 3 lety +15

    Keep them coming! You’re doing a great job

  • @pranavkul525
    @pranavkul525 Před 2 lety +6

    Thanks a lot. The video was really helpful and the way you explain it is so great

  • @duvincent869
    @duvincent869 Před 2 lety +6

    Imagine array as people line up and facing a wall, whenever a person want to join the queue, we can either choose a person, push him back and sit in front of him, or join at the end of the queue.
    The natural of array list cause that, we are searching right (I am bigger than you, then I join behind you so i + 1), if we are searching left (I am smaller than you, I don't have to move but push you behind as i).
    That is why we can always choose the lower bound pointer. At first I am thinking why god create left and right bound unequally.

  • @ruksharalam173
    @ruksharalam173 Před rokem +1

    One o' the best LeetCode channels in YT

  • @lylelll2275
    @lylelll2275 Před 3 lety +6

    like your videos! They are easy to understand.

  • @abdullahahmad5838
    @abdullahahmad5838 Před 2 lety +2

    I did something like this:
    def binary(list1, key):
    start = 0
    end = len(list1) - 1
    while start list1[mid]:
    start = mid + 1
    elif key < list1[mid]:
    end = mid - 1
    # print(mid)
    if key > list1[mid]:
    return mid + 1
    elif key < list1[mid] and mid > 0:
    return mid
    else:
    return 0

  • @mohammadjaffar4461
    @mohammadjaffar4461 Před 5 měsíci +1

    for a moment i was feeling really dumb, i tried different ways and stuck for about 45 mins, then i saw ur explaination,, i wonder why this logic didn;t hit me ,, im feeling really dumb😓😓

  • @Oyeah900
    @Oyeah900 Před 3 lety +5

    I am confused about when to use (less than)< vs

    • @ravivanam7868
      @ravivanam7868 Před 2 lety

      left and right pointers define the range in which the target lies. so if left is 3 and right is 12 then the target could be at any index from 3 to 12 including 3 and 12. now imagine what happens when left = right = some number, say 4 then the target could be at any index from 4 to 4 including 4. see it? it means it must be at 4(=left = right).

    • @HuangweiHenryFang
      @HuangweiHenryFang Před 2 lety

      I am also confused with it. What I understand is that it depends on how you move your boundary. If you don't set the boundary over the mid (e.g left = mid, but not left = mid+1), you should be careful about using

  • @user-he2ui5bx2c
    @user-he2ui5bx2c Před 2 lety +2

    Thank you sir. i am kotlin user but its really impressive thank you

  • @skms31
    @skms31 Před 2 lety +2

    Who invents these problems !! Crazy stuff

  • @thinja
    @thinja Před 2 lety +1

    wow that trick at the end was *chefs kiss*

  • @huyhoangnguyenhuu2136
    @huyhoangnguyenhuu2136 Před rokem +1

    great explanation. Very appreciate!!

  • @Famelhaut
    @Famelhaut Před 11 měsíci

    1 liner:
    import bisect
    class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
    return bisect.bisect_left(nums, target)

  • @srinathreddy1727
    @srinathreddy1727 Před 10 měsíci

    Very well explained like why we should left, why not right??
    Thanks a lot❤

  • @youtubeDaddy525
    @youtubeDaddy525 Před 3 lety +2

    Well explained !

  • @Priyam6F4
    @Priyam6F4 Před rokem

    Approach
    The problem is little bit modified when compared to finding the floor/ceil of an element using binary search. Usually to find the floor,(Here I am assuming you know the basic binary search concept of finding the floor and ceil) we consider the rightmost search space.
    if(nums[mid]

    • @_DashingAdi_
      @_DashingAdi_ Před rokem

      Floor of 5 is 4? dafuq

    • @Priyam6F4
      @Priyam6F4 Před rokem

      @@_DashingAdi_ Intelligent man, by floor I mean, the closest minimum, big brain time

  • @averychen4633
    @averychen4633 Před 7 měsíci

    for me the hardest is not the algorithm, it is the extreme cases such as nums=[1] and the boundaries. I absolutely hate 0 index!

  • @user-zv3mr7bo1d
    @user-zv3mr7bo1d Před 2 měsíci

    It was really hepful

  • @szymon200000
    @szymon200000 Před 3 lety +1

    one of the things I noticed when solving this problem is that if the target is less than nums[0] you should return 0, and if the target is greater than nums[len(nums)-1], to return len(nums). do you think this is efficient or just a waste of space/time?

    • @ravivanam7868
      @ravivanam7868 Před 2 lety +5

      waste of space and time cuz the code would still work when target is out of bounds

    • @_DashingAdi_
      @_DashingAdi_ Před rokem

      ​​@@ravivanam7868ardon me if this is a dumb question but how would the code still work if the target is out of bounds, won't the program stop executing after it returns 0?

  • @meowmeow21588
    @meowmeow21588 Před rokem +1

    Not me patching up six conditions like the transformers in Transformers 2 that joined together to barely crawl pass through the finish line and guy just does a regular binary search QAQ

  • @lamedev1342
    @lamedev1342 Před 2 lety +1

    Cool solution. I only looked at this once i finished my solution.
    Mine was basically implement binary search, and if it doesnt work, there are 3 cases to take account for.
    Code:
    begin = 0
    end = len(nums) - 1
    last_value = len(nums) - 1
    first_index = 0
    while begin target:
    end = midpoint - 1
    else:
    return midpoint

    for i in range(len(nums)):
    if target > nums[last_value]:
    return last_value + 1
    if target < nums[first_index]:
    return 0
    if nums[i] < target < nums[i+1]:
    return i+ 1

  • @SeyyedMohammadLoghmanDastgheyb

    Hi 🙂 this solution doesn't work for 👉 nums=[1, 3, 5, 6], target=2 😵‍💫 What am I missing? 🧐

  • @lucasjackson7647
    @lucasjackson7647 Před 2 lety

    you should explain that // will only keep the whole number component

  • @canr
    @canr Před 3 lety +3

    great video. I have one small question though. why do we add or subtract 1 from mid?

    • @sravanikatasani6502
      @sravanikatasani6502 Před 3 lety +11

      we are updating the range to search here.. if the target is not equal to element at position mid, we can say that it has to lie either on left or right side of mid ,i.e search area will half of the previous. if target is less than mid then we search on left side with right=mid-1 ( we are not considering element at mid because we already checked if target== element at mid) and the other case left=mid+1 if target> element at mid.

  • @biomed3d503
    @biomed3d503 Před rokem

    at 12:50, I am still not clear why left becomes 1 since the shift has not occured, so left should remains at 0. Any help with better explantion? thnks

    • @adamgertzkin1715
      @adamgertzkin1715 Před rokem

      The state where L=R is one step before the algo will end. We have: while(L

  • @kirich321
    @kirich321 Před 2 lety +2

    is there a recursive function solution?

    • @DomKeon
      @DomKeon Před rokem

      Recursive kotlin solution:
      fun searchInsert(nums: IntArray, target: Int): Int {
      return helper(nums, target, 0, nums.size - 1)
      }
      private fun helper(nums: IntArray, target: Int, left: Int, right: Int): Int {
      val middleIndex = (left + right) / 2
      if (nums[middleIndex] == target) return middleIndex
      if (left > right) {
      return left
      }
      return if (target > nums[middleIndex]) {
      helper(nums, target, middleIndex + 1, right)
      } else helper(nums, target, left, middleIndex - 1)
      }

  • @xvarmond
    @xvarmond Před rokem

    Thanks you!

  • @mageshiz7346
    @mageshiz7346 Před rokem

    Thank you sir

  • @aliadel1723
    @aliadel1723 Před rokem

    you are the best ♥

  • @xingdi986
    @xingdi986 Před 3 lety

    in case the target does not exist in the array, can we check the target value with the most left and right value first and then do the binary search?

    • @ssshukla26
      @ssshukla26 Před 3 lety

      that is O(n) operation, so we cannot check.

    • @ravivanam7868
      @ravivanam7868 Před 2 lety

      the time complexity wouldn't change if you did, but it is unnecessary.

  • @issamuhsen1245
    @issamuhsen1245 Před rokem +1

    Why not do this:
    If target in nums:
    Return nums.index(target)
    Else:
    nums.append(target)
    nums.sort()
    Return nums.index(target)

    • @Saotsu1
      @Saotsu1 Před rokem +2

      This is slow as hell, the purpose is a efficient solution

    • @issamuhsen1245
      @issamuhsen1245 Před rokem

      @@Saotsu1 on leetcode it says that the runtime is 102 ms and it beat about 46 percent of submissions. It that slow?
      I heard that leetcode sometimes give random numbers about submissions

    • @Saotsu1
      @Saotsu1 Před rokem +1

      @@issamuhsen1245 Your code will run with O(N), which isn't slow, but very slow compared to O(log n)

    • @issamuhsen1245
      @issamuhsen1245 Před rokem

      @@Saotsu1 thanks for help

  • @rajeshadam978
    @rajeshadam978 Před 2 lety

    thanks

  • @scpcomm1215
    @scpcomm1215 Před rokem +1

    i would have never come out with this lol. Maybe, i would have studied computer science and all i did was code and learn a gang of techniques and thrive to always come out with new ways to make algorithms ran faster and more efficient...crazy, respect to you mah software engineeris, programmers or whatever you are. honestly , im happy with iteration throught the entire loop lol Doesn't that make more sense haha. jk, ima memorize this technique like people memorize Maradona and Magico Gonzales tricks and then show the world

  • @hamoodhabibi7026
    @hamoodhabibi7026 Před 2 lety

    left you mad man xD. ur the best

  • @gunahawk6893
    @gunahawk6893 Před 2 lety

    bro please do a dsa course in python

  • @funfingen
    @funfingen Před rokem

    When I submit this solution, it beats only 47% in runtime... Why do you think that's the case?

  • @RajeshSingh-zc6ct
    @RajeshSingh-zc6ct Před rokem

    what if we have duplicate values??

  • @CST1992
    @CST1992 Před 4 měsíci

    Now they specify that they *require* logarithmic time complexity in the problem itself.

    • @doc9448
      @doc9448 Před 4 měsíci

      Literally. And it's still an easy.

    • @CST1992
      @CST1992 Před 4 měsíci

      @@doc9448 Yeah, it still is. Because it's a very basic application of binary search.

  • @jackbaker995
    @jackbaker995 Před 5 měsíci

    he's breathing so hard at the end lol. It really is a difficult question though, from a beginner like me at least.

  • @SaadQureshiOfficial
    @SaadQureshiOfficial Před rokem

    I don't understand the return L part.

  • @joydeep_
    @joydeep_ Před 26 dny

    🤑🤑🤑

  • @aditi1786
    @aditi1786 Před měsícem

    #completedbyaditi2206

  • @sanooosai
    @sanooosai Před 6 měsíci

    thank you