Find Minimum in Rotated Sorted Array - Binary Search - Leetcode 153 - Python

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

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

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

    🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤

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

    Shorter code (don't need to initialize a results variable, since we know that the while loop will break when left pointer is pointing at the minimum):
    def findMin(self, nums: List[int]) -> int:
    l, r = 0, len(nums) - 1
    while l < r:
    m = l + (r - l) // 2
    if nums[m] > nums[r]:
    l = m + 1
    else:
    r = m
    return nums[l]

    • @Rob-in7vp
      @Rob-in7vp 2 ปีที่แล้ว +14

      thanks, this solution made more sense to me

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

      Hey I tried this, but it doesn't work for this set of nums:
      nums = [12, 0, 1, 2, 3, 4, 5, 6, 9, 10, 11]

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

      @@christianmorabito4148 works on my end 🤔

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

      @@Grawlix99 Oh yes!! Sorry, I was returning m (mid variable) instead of l (low variable).

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

      @@christianmorabito4148 np! 😃

  • @world11191
    @world11191 10 หลายเดือนก่อน +68

    I've watched this video probably 10-15 times over different days, and only now is it starting to make sense. Bless.

    • @regnam503
      @regnam503 9 หลายเดือนก่อน +13

      In all fairness, this particular explanation is not the most intuitive. Still grateful tho.

    • @luiggymacias5735
      @luiggymacias5735 6 หลายเดือนก่อน +2

      if you dont know what binary search is, i would recommend to learn that first, the problem becomes more easy to understand if you know about that, and this explanation makes more sense if you try around 40 minutes to solve it by yourself, even if you dont get to the answer, the important thing is to solve it conceptually, even if you dont get to solve it with code

    • @mattk.9937
      @mattk.9937 3 หลายเดือนก่อน +1

      There is a much easier solution that I came up with:
      class Solution:
      def findMin(self, nums: List[int]) -> int:
      p1 = 0
      p2 = 1
      for i in range(1, len(nums)):
      if nums[p1] > nums[p2]:
      return nums[p2]
      p1 += 1
      p2 += 1
      return nums[0]
      You just set two pointers to the first and second elements and then update them through each iteration. If at any point the first pointer is larger than the second, you know the second is the minimum value due to the fact that the list is sorted.

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

      @@mattk.9937 that's o(n) solution, problem prompts you to solve it o(logn)

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

      @@mattk.9937 that's a good solution but not O(log n) time

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

    Dear NeetCode, Thank you so much for your videos! The quality and comprehensiveness of your explanations is incredible. For every problem I solved or struggle to solve I will instantly turn to your videos. I won't even consider other TH-camrs because I know that your explanations are the best. Thank you for this quality content!

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

    I really hate Binary Search problems, Binary search by itself is simple, but its implemented in so many different weird ways, which make it really dumb..

    • @crosswalker45
      @crosswalker45 ปีที่แล้ว +9

      I bet u hate dp too by that kinda logic 😂

    • @sarvagyadwivedi2467
      @sarvagyadwivedi2467 ปีที่แล้ว +15

      @@crosswalker45 don't we all hate dp

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

      @@sarvagyadwivedi2467 haha.. True

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

      You couldn't be more accurate. It's like you have to come up with a different implementation of binary search for every problem.

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

    You can skip the first if condition by doing this:
    Instead of comparing mid pointer with left, compare it with right (all other factors remain same).
    For example: [4,5,6,7,0,1,2]
    Iteration 1:
    start pointer (s) = 0
    end pointer (e) = 6
    mid pointer (m) = (s+e)//2 =3
    here, nums[m] >= nums[e]:
    therefore, s=m+1
    Iteration 2
    s=4
    e=9
    m = 5
    here, nums[m]

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

      i like this

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

      I agree, I was thinking this too. What if they rotated it n times and it is back to its original sorted state where the leftmost element is the smallest. If we compare mid to the right, and see if mid is bigger, then go right, else go left

    • @JamesBond-mq7pd
      @JamesBond-mq7pd 8 หลายเดือนก่อน

      doesn't work for [3,1,2]

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

      @@JamesBond-mq7pd yeah when searching left, e has to be set to m instead of m-1

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

      Wayy more intuitive, thank you bro

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

    more consice solution:
    def findMin(self, nums: List[int]) -> int:
    l, r = 0, len(nums)-1
    while l=nums[r]:
    l = mid+1
    else:
    r = mid
    return nums[l]

    • @JasonKim1
      @JasonKim1 5 วันที่ผ่านมา

      Although your answer is more concise, I think it's less efficient than NC's answer.
      For example, in a perfectly sorted array, NC's answer is O(1). Your answer still will be O(log(n)).

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

    Thank for explaining this very clearly.
    With a minor tweak I was able to solve following as well.
    154. Find Minimum in Rotated Sorted Array II

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

      Curious about how you modify the code to make 154 work. Do you mind sharing the script?

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

      @@lxu5148 I tried to add pastebin link here but keeps getting deleted.
      But this is what my if condition looks like
      if(nums[lo] == nums[mi] && nums[mi] == nums[lo])
      return Math.min(findMin(nums, res, lo, mi-1), findMin(nums, res, mi+1, hi));
      else if(nums[mi] >= nums[lo]) // If mid is greater then everything on left, the look on right side
      lo = mi + 1;
      else
      hi = mi - 1;

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

      @@hrvmhv4391 appreciate it! I will check it when I am with my laptop.

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

      ​@@hrvmhv4391
      (nums[lo] == nums[mi] &&
      nums[mi] == nums[lo])
      ? didn't get it. isn't that the same condition?

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

      @@lxu5148 so, did it work?

  • @spageen
    @spageen 3 หลายเดือนก่อน +2

    The way I like to think about it is we're searching for the point where the sorted array 'resets' to the minimum. If the middle is less than the leftmost value, that means the 'reset' point is somewhere on the left side. Otherwise, it's on the right side.

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

    you can actually do if m > r search right or if m > l search right. Either one works with the case added for the already sorted array

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

      because of how the sorted array and rotation works, if the inflection point is to the left of M, L and R are always larger than M, but if the inflection point is to the right of M, L and R are always smaller than M.

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

    Beautiful Explanation. I used the same code for the 154. Find Minimum in Rotated Sorted Array II with just one change and it was accepted.
    Since in 154 problem, there are duplicates as well, I added an extra check in case all elements at start, mid and end are the same. In that case, we just decrement the end pointer by 1. Otherwise, the code remains the same.
    while start = nums[start]: start = mid + 1
    # Otherwise, we will find the minimum on the left side
    else: end = mid - 1

  • @Byte-ul
    @Byte-ul 2 ปีที่แล้ว +20

    Just move right to mid, instead of mid -1 and you won't need to check for min result.

  • @ritiksaxenaofficial
    @ritiksaxenaofficial 7 หลายเดือนก่อน +5

    Great explanation

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

      My code:
      class Solution:
      def findMin(self, nums: List[int]) -> int:
      low = 0
      high = len(nums)-1
      while low

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

    hmmm the condition to determine if arr[mid] is in the first sequence to be arr[mid] > = arr[start] is not enough. Counter example: [4,5,6,7,0,1,2], l = 0, r = 6, mid = 3, after first update, start = mid + 1 which is 0, we are searching in subarray[0, 1, 2]in this case arr[mid] > arr[start] still holds, but it is in the second sequence. The only reason that your solution passed is because you're updating the result all the way.

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

      He explained in the video that this condition does not work on sorted lists. The reason it still passes is because he has the nums[l] < nums[r]

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

    Thx NeetCode, here is my solution:
    class Solution:
    def findMin(self, nums: List[int]) -> int:
    left, right = 0, len(nums)-1
    while left < right:
    mid = (left+right) // 2
    if nums[mid+1] < nums[mid]:
    return nums[mid+1]
    # left sorted
    if nums[mid] > nums[left]:
    # search on right
    left = mid + 1
    # right sorted
    else:
    # search on left
    right = right - 1
    return nums[0]

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

      Does this work for [5, 1, 2]?

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

      shoot i guess it does

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

    Works for edge cases where min as middle and [2,1]:
    class Solution:
    def findMin(self, nums: List[int]) -> int:
    ans=nums[0]
    l,r=0,len(nums)-1
    while l

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

    After watching the solution of problem 33 I solved this problem on my own! However your solution is always the best, I could learn from it a lot!

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

    My solution:
    def findMin(self, nums: List[int]) -> int:
    l, r = 0, len(nums) - 1
    while l < r:
    m = (l + r) // 2
    if nums[m] < nums[r]:
    r = m
    else:
    l = m + 1
    return nums[l]

  • @rustamkarimov1191
    @rustamkarimov1191 11 หลายเดือนก่อน +1

    The most effective I suppose would be:
    const foo = nums => {
    // [4,5,6,7,0,1,2,3]
    let [l, r] = [0, nums.length - 1]
    while (l < r) {
    let m = Math.floor((l+r) / 2)
    if (nums[m] >= nums[r]) l = m + 1;
    else r = m;
    }
    return nums[l];
    }

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

    i found more shorter way:
    class Solution:
    def findMin(self, nums: List[int]) -> int:
    l, r = 0, len(nums) - 1
    while l

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

      wow this is so much better and is way easier to remember

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

    You state the rules:
    "If our middle pointer happens to be in the right sorted portion, then we want to search to the left; **if our middle is in the left sorted portion we want to search to the right**".
    And later state:
    "If we ever got to a portion of the array that's completely sorted we would just **take the leftmost value and see if it's smaller than the current result and stop our binary search.**"
    This statement completely conflicts with the algorithm of focus, which says **if the leftmost value is smaller we search to the right**. So do we search to the left or "stop our binary search"?
    So are there two algorithms rules at play here or what? I'm guessing yes, but you said an entirely conflicting rule pretty flippantly without clarifying this is an important rule caveat and consideration.

  • @ShubhamMishra-mz4zw
    @ShubhamMishra-mz4zw ปีที่แล้ว +3

    One of the best explanation of this problem. Thank you ❤

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

    This is one of the first medium problems that I correctly new the intuition. LETS GOO

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

    are there people who have never seen this before and just came up with the solution on the spot? Kudos man

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

      I was able to come up with one before seeing the solution but I spent a couple hours going through examples and noticing patterns to think of the solution. Wouldn't be able to come up with it on the spot yet, but I guess that's why we practice!

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

      Well, if we weren't so caught up in trying to learn/solve it with binary search we could actually just look for the minimum number with one for loop 🤷‍♂

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

    Your explanation is very good. Line no 7, condition should be if (nums[l]

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

      I got this too, good catch.

  •  3 ปีที่แล้ว +24

    I'm not sure this applies on Python, but when we calculate the middle element, I think it would be better to write;
    middle = left + (right - left) / 2;
    instead of
    middle = (left + right) / 2;
    to prevent arithmetic overflow.
    en.wikipedia.org/wiki/Binary_search_algorithm#Implementation_issues

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

      Thats definitely a good point!

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

      python don't have int overflow issue. java and cpp definitely need left + (right - left) / 2

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

      That's right. That's how we know a senior and a junior

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

      @@mindsetnuggets what joy did you get in putting him down, man? we all gotta learn to be more humble human beings

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

      could be a good practice, but the input list is constrained to max 5000 elements

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

    Ha! Solved this on my own, my code worked but was a bit wonky. Good to see this video :)
    I spotted the pattern of if a part was steadily increasing or not.
    I didn't use the midpoint to determine any values, I just used it as a pivot and ultimately would return l or r :')
    Here's my wonky code (it works!)
    var findMin = function(nums) {
    let l = 0
    let r = nums.length - 1
    while (r - l > 1) {
    let m = Math.trunc( (l+r) / 2)
    const [isLeftIncreasing, isRightIncreasing] = isSteadilyIncreasing(nums[l], nums[m], nums[r])
    if (isLeftIncreasing && isRightIncreasing) return nums[l]
    else if (isLeftIncreasing) { //pick right
    l = m
    }
    else if (isRightIncreasing) { //pick left
    r = m
    }
    }
    if (nums[l] >= nums[r]) return nums[r]
    else if (nums[l]

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

    I have another solution based on his logic where I don't keep track of the min res value:
    l, r = 0, len(nums)-1
    while nums[l] > nums[r]:
    mid = (l+r)//2
    if nums[mid] >= nums[l]:
    l = mid + 1
    else:
    r = mid
    return nums[l]

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

    Firstly: you're a genius, thanks for sharing so much on YT.
    Today LC came up with a use case [3,1,2] for this problem which breaks the `mid + 1` or `mid - 1` logic in this case where the answer is mid but given LEFT > MID we would to to index 0 and miss the correct answer.
    A little tweak on the original code should suffice tho':
    def findMin(self, nums: list[int]) -> int:
    if len(nums) == 1:
    return nums[0]
    left, right = 0, len(nums) - 1
    while left = nums[left]:
    left = mid
    else:
    right = mid

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

      it still works right? the answer is MID but LEFT > MID, we capture the minimum already by doing min(res, nums[mid]) before comparing LEFT > MID... the minimum will remain as 1 throughout the entire loop. Your answer is a little better as we don't need to store a variable for the mininum value and perform a comparison to get the minumum value per loop. Great job!

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

      Hey GUstavo, thanks for your insight! I would love to talk to you more about problem solving. Is it possible I can contact you in any way like DIscord or Twitter?

  • @TheRandomdude136
    @TheRandomdude136 11 หลายเดือนก่อน +2

    I have a simpler alternative that allows you to not keep track of the minimum, here it is:
    class Solution:
    def findMin(self, nums: List[int]) -> int:
    start, end = 0, len(nums) - 1
    while start - end > 1: # if middle exists
    mid = (start + end) // 2
    if nums[mid] > nums[end]:
    start = mid + 1
    else:
    end = mid
    return min(nums[start], nums[end])

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

    Unfortunately this algorithm does not work for test cases such as:
    [2,1] or
    [3,1,2]

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

    class Solution {
    public:
    int findMin(vector& nums) {
    sort(nums.begin(),nums.end());
    return nums[0];
    }
    };

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

      since the best sorting algorithm is nlogn , your solution is going to be nlogn , which is worse than linear search(n) let alone binary search (logn)

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

    I did this solution quite different by checking if middle is < middle-1 I can itentify the lowest number:
    def findMin(self, nums: list[int]) -> int:
    l, r = 0, len(nums) - 1
    while l nums[r]:
    l = middle+1
    else:
    r = middle-1
    return nums[l]

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

    Why do we update res on line 12 after getting the middle point?

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

      mid pointer is always pointing to the potential minimum value in the array. Therefore, you want to keep updating the res variable to be checked against the new mid pointer value each iteration.

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

      Check the case discussed from 9.06. that will answer why we need to update res.
      If res would not have been updated, we would get min as 3 instead of 1 in this case.

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

    i think you should clarify what right portion and left portion is if you're referring to the original array sorted

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

    Doesn't initializing right pointer to the end of the array itself take O(n) time? Languages like Python might have under the hood optimizations to do this more efficiently, but from algorithmic perspective, if we have to iterate through the array once to initialize the right pointer, wouldn't it be more efficient to just find the minimum in that iteration itself?

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

    My solution which I think is more intuitive:
    class Solution:
    def findMin(self, nums: List[int]) -> int:
    start , end = 0 ,len(nums) - 1
    curr_min = float("inf")

    while start < end :
    mid = (start + end ) // 2
    if(nums[mid+1] < nums[mid]):
    return nums[mid+1]

    # right has the min
    if nums[mid] > nums[end]:
    start = mid + 1

    # left has the min
    else:
    end = mid

    return nums[start]

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

      I had something similar.

  • @Suraj-wt8hn
    @Suraj-wt8hn ปีที่แล้ว +1

    Nice Explanation!!
    Another approach in O(logn) time will be Two pointer strategy, I solved it using the following approach

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

    Thanks

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

    while(l Think why!
    else h = mid;
    }
    }
    For anyone who is struggling, I break these type of questions to 2 cases. (mid is in sorted sub_array, mid is not in sorted_subarray). Write cases accordingly!

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

    Not sure why, but simply using "return min(nums)" (in Python) seems to run faster than the binary search algorithm solution.

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

      what is "min" doing under the hood?

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

      *'min' use O(N) time to search for the minimum element in an array.
      * It uses linear search.
      * The time taken shown in leetcode doesn't provide you the actual time taken.

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

      @@adarshvats8003 but in this solution, instructor used min function so what's point of using in code then using in first place.

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

      @@vaishaliagrawal4781 min(array) gives you minimum of array in O(N) but if we write min(x, y) gives minimum in O(2) which is a linear operation.
      Thus the code still remains O(logn).
      I hope this helps!!

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

      @@adarshvats8003 Thanks, make sense

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

    Is the EQUAL SIGN in "(nums[l] >= nums[m])" ONLY for the case of an input like [2,1] where l=0, m=(0+1)//2 = 0 but we randomly need to check the other index value too "just because" (outside of our actual defined rules we've outlined)... just to make sure?

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

    easy way : while l < r:
    m = (l + r) // 2
    if nums[m] > nums[r]:
    l = m + 1
    else:
    r = m
    return nums[l]

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

      This is for sorted and not rotated array iguess

    • @KumarMukand-dm9iw
      @KumarMukand-dm9iw 2 หลายเดือนก่อน

      @@numanali8545 No it is for rotated!

    • @user-gh2gw8cx2b
      @user-gh2gw8cx2b หลายเดือนก่อน

      @@KumarMukand-dm9iw that is such a more concise solution, thanks!

  • @JamesBond-mq7pd
    @JamesBond-mq7pd 8 หลายเดือนก่อน

    MORE EASIER WAY!
    def findMin(self, nums: List[int]) -> int:
    res = float("inf")
    l, r = 0, len(nums) - 1
    while l nums[r]:
    l = m + 1
    else:
    r = m - 1
    return res

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

      you can just return nums[L] at the end and avoid the res

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

    Why do we need line 12, `res = min(res, nums[m])`?
    Wouldn't it be caught if we just assigned `l = m` or `r = m` instead of `= m ± 1`?

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

      I think because it saves time. Example has just 5 inputs so it might seem to be less useful.

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

      @@ganeshkamath89 I've been practicing it without storing the minimum result for a few months now. I don't think you need to store the minimum. I just return the `nums[m]` value.

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

      @@PippyPappyPatterson Thanks. You are right. I tried this code change and it worked for me also 😀

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

      @@ganeshkamath89 ofc, good luck internet traveler

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

    The code presented in the video is incorrect, it's different from even the Python code submitted on the website. Can you please fix the video?

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

    def findMin(self, nums: List[int]) -> int:
    bad = -1
    good = len(nums) - 1
    while good - bad > 1:
    candidate = (bad + good) // 2
    if nums[candidate] < nums[good]:
    good = candidate
    else:
    bad = candidate
    return nums[good]

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

    No need to do any storing and comparing.
    Simple Binary searching here..
    def findMin(nums,l,h):
    mid= (l+h)//2
    if(nums[l]nums[h]):
    return h
    return findMin(nums,l,mid)

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

    You mention that the left sorted portion is always going to have values > the right sorted portion. In the event that the array has not been rotated or rotated n - 1 times (which would produce the same array) then wouldn't that statement not be true? Ex: [0,1,2,3,4,5,6,7] ... m = array[4] ... array[4] == 3 ... 3 >= 0 ... we are in the left sorted portion ... all values of the right sorted portion are greater than the left. Maybe I am confused but if someone could clarify I would greatly appreciate it.

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

      Sorry at 8:00 he cleared this up. In the event that left < right then we are in a sorted array. Given left < result then result = left return result.

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

    The funny thing is I test my naive solution which o(n) in Javascript:
    function min(nums) {
    return Math.min(...nums);
    }
    and it beats 23% of other solutions which used binary search 🤣

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

    What about this [5,1,2,3,4,]
    Not every value in the left portion is bigger than in the right portion

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

    Is it safe to assume that if a search requires O(log n) time and the list is ordered. It's most likely a binary search in some flavor or another?

    • @rustamkarimov1191
      @rustamkarimov1191 11 หลายเดือนก่อน +2

      it's in fact 100% binary search

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

    lost when you just assume mid will be at 1? how can you explain the set up

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

    C++ solution:
    class Solution {
    public:
    int findMin(vector& nums) {
    int i = 0 ;
    int j = nums.size() - 1;
    int mid = (i+j)/2;
    if(nums.size()==1)
    {
    return nums[0];
    }

    /*
    idea: use binary search.
    If the value to left of mid is smaller than the right pointer, then
    move right pointer to mid
    Otherwise, move left pointer to mid
    */
    while(i

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

    Thank you very much man

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

    Can I use same algorithm as search in rotated sorted array

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

    Hey, I had quick question. Since the problem statement asks us to solve this in O(logn), don't you think using min() function (which O(m)) make this O(mlogn) ?

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

      Ahh, got it. min() for two values is O(1). Thanks

  • @CameronSantiago-w6i
    @CameronSantiago-w6i 8 หลายเดือนก่อน

    Your videos are the best

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

    ```
    def findMin(self, nums: List[int]) -> int:
    left = 0
    right = len(nums) - 1
    while (left < right):
    mid = (left+right)//2
    if (nums[mid]

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

    I hope you can make a video about Binary Search Templates and help us understand it better. Thank you.
    class Solution:
    def findMin(self, nums: List[int]) -> int:

    low, high = 0, len(nums) - 1

    while low < high:
    mid = (low + high) // 2

    if nums[mid] < nums[high]:
    high = mid
    elif nums[mid] > nums[high]:
    low = mid + 1
    return nums[high] #nums[low]

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

    U a BST God🎉

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

    Good explanation, however, I think we can improve it keeping L and R, but looping length/2 times in both direction, if nums[L] > nums[L+1] then L is the position of the minimum or if nums[R] < nums[R-1] then position R holds the minimum:
    // C#
    for (int i = 0, j = nums.Length - 1; i < nums.Length / 2; i++, j--)
    {
    if (nums[i] > nums[i + 1]) return nums[i + 1];
    if (nums[j] < nums[j - 1]) return nums[j];
    }
    return nums[0];

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

    class Solution:
    def findMin(self, nums: List[int]) -> int:
    low, high = 0, len(nums) - 1
    while low < high:
    mid = (low + high) // 2
    if nums[mid] > nums[high]:
    low = mid + 1
    else:
    high = mid
    return nums[low]

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

      I tried this too which I thought was great, but it doesn't work for this list:
      nums = [12, 0, 1, 2, 3, 4, 5, 6, 9, 10, 11]

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

      Sorry, I was returning m (mid variable) instead of l (low variable).

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

    thanks, clear illustration

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

    Waiting for your 752. Open the Lock video. Thanks in advance.

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

      ur in luck he just uploaded it

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

    after the condition if nums[m] >= nums[l]: you need to update res to nums[l] because according to the condition it is less than nums[m](our current res) and this is the last time we'll be visiting the current nums[l] (since we update l to m+1)

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

      We are always terminating if nums[l] < nums[r] to handle this, so there is no need to explicitly check nums[l] at each iteration. For instance if nums[m] >= nums[l] we know that nums[l] is also greater than or equal to nums[r] (because we checked this condition first)... therefore there is no way nums[l] at that point will be the minimum result since there is a smaller value on the right side of the array and we update l to mid + 1 to search the right side.
      Put more simply... because we always check nums[l] < nums[r] we are always guaranteed to terminate and set the result to nums[l] if nums[l] is ever the min.

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

    It does not work for case when minimum is at mid. e.g: [3,1,2]

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

      does it even work for [1,2,3] ?

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

    Thank you!

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

    Thank you for your valuable time. I really appreciate.
    If anyone is looking for Java Code:
    public static int findMinimum(int[] input) {
    if (input == null || input.length == 0) {
    throw new IllegalArgumentException("Invalid input passed");
    }
    int left = 0, right = input.length - 1, mid = 0;
    while (left != right) {
    mid = (left + right) / 2;
    if (input[mid] >= input[left]) {
    left = mid + 1;
    } else {
    right = mid - 1;
    }
    }
    return input[mid];
    }

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

    class Solution:
    def findMin(self, nums: List[int]) -> int:
    try:
    for ele in range(len(nums)):
    if nums[ele] > nums[ele+1]:
    return nums[ele+1]
    except:
    return nums[0]

  • @AryanRao-v3h
    @AryanRao-v3h หลายเดือนก่อน

    return min(nums) works as well

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

      no its doesn't, that's not log n time complexity, thats n. Even though it passes in leetcode it's wrong due to the problem constraints.

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

    Great explanation!

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

    return min(nums) did the trick for me but I don't think thats intended

    • @Rahul-eh3rf
      @Rahul-eh3rf 2 ปีที่แล้ว +5

      No because that is not in O(log n)

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

      @@Rahul-eh3rf What about my code here:
      l, r = 0, len(nums) - 1
      while l < r:
      if nums[r] > nums[r - 1]:
      r -= 1
      elif nums[r] < nums[r - 1]:
      return min(nums[l], nums[r])
      if l == r:
      return nums[l]
      # if nums[r] can move down then keep nums[l]
      # if nums[r] cannot move down compare value with nums[l] and return smallest value
      # if index l and index r are the same, return nums[l]
      everything fine? It passes all test cases but not sure if O(log n).

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

      @@Lambyyy It's O(n) because you are essentially comparing every num against left num. A O(logn) solution is possible here if the problem size is halved every step.

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

      @@tahsinamio2639 Ah okie, thank you!

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

    Why does it not work for [3,2 ]?

  • @ShefaliShrivastava-e8x
    @ShefaliShrivastava-e8x 2 หลายเดือนก่อน

    Isn't the time complexity of min() function O(n), which kinda defeats the purpose of using binary search to find the solution in O(logn)? If we must use min(), we can just do `return min(nums)` at that point?
    Someone please explain, I am a little confused. Thanks!

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

      when using min(x,y) for only two values, it is constant time but if you give it a list, it will be O(n)

    • @ShefaliShrivastava-e8x
      @ShefaliShrivastava-e8x 27 วันที่ผ่านมา

      @@Shonia Oh that makes sense - thank you!

  • @RN-jo8zt
    @RN-jo8zt 9 หลายเดือนก่อน

    here we are doing r=mid instead of r=mid-1?

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

    I did Arrays.sort(nums);
    return nums[0]; :D :D

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

    hm..does len(arr) count as time complexity of O(N)?

  • @will-iy9gu
    @will-iy9gu หลายเดือนก่อน

    damn this problem broke my brain for some reason lol

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

    int low = 0, high = arr.size() - 1;
    int ans = INT_MAX;
    while (low

  • @mihaieugen1280
    @mihaieugen1280 8 หลายเดือนก่อน +2

    Bro breathe

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

      Why

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

    You're the best

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

    If an array is rotated to the its size times then this may verdict your answer

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

      what does 'verdict' your answer mean?

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

      @@djSubzz the answer may be wrong.

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

    Isn't binary search already log(n) why not just sort it?

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

      Oh sorting is nLog(n)

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

    You are awesome

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

    thnak you

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

    My gawd, every one of these binary search problems I get some edge cases wrong due to these tiny but important details of settings r = m (instead of m - 1) or having l start from 1 instead of 0 (koko eating bananas). It's super frustrating

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

      don't worry you'll get there. one step at a time

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

      @@jasonahn8658thanks man.

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

    May I know why you use // instead of / in m.

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

      In python a single '/' will evaluate to decimal division (e.g. 1 / 2 = 0.5), where as '//' evaluates to integer division which is the default for most languages (e.g. 1 / 2 = 0)

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

    Why not implement the binary search recursively rather than using the while loop? It's still O(logn) right?

  • @podgorniy.r
    @podgorniy.r ปีที่แล้ว

    2:29
    3:18
    8:05

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

    min(nums) got accepted)

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

    Such a great explanation!

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

    Can you do binary cameras tree leetcode?

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

    understood

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

    Thanks for the explanation. One point of feedback I would recommend is to cut down or outright stop saying the word "right" when you're not talking about the direction. It can get confusing in problems in which the left/right directions are crucial to explaining the solution (e.g. this solution or tree related solutions).
    Every time you say "right", we have to differentiate between the direction and you confirming something which just adds extra noise to your explanation

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

      Good point for some people.
      For me, I am used to his kind of speech pattern and maybe being a native English speaker it helped me not be distracted by it, but it could be a problem for ESL people or just for people who don't speak/think in that pattern.
      Learning is already complicated, so additional barriers when unnecessary can be frustrating.

  • @ak001ify
    @ak001ify 15 วันที่ผ่านมา

    Did not understand at first so confused

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

    please code using c++ too

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

    1 line solution,
    just ""return min(nums)" thats it

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

      bro o(logn) is the requirement. you are mentioning o(n) approach

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

    gd video!

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

    I like all of your videos I watched so far except this one. You talked too fast, and I'm lost where you said if the middle is 1 then search on the left.