Find Peak Element - Leetcode 162 - Python

Поделиться
HTML-код
  • Опубликовано: 7 фев 2025

Комментарии • 89

  • @mirceafeder4945
    @mirceafeder4945 9 месяцев назад +86

    RIP to all those who got this in an interview without solving it before

    • @tuandino6990
      @tuandino6990 6 месяцев назад +5

      I think if the interviewer mention o logn, it will be very straightforward

    • @harshalyallewar
      @harshalyallewar 5 месяцев назад

      @@tuandino6990 still it would be challenging to approach with binary seach

    • @yashshukla1637
      @yashshukla1637 4 месяца назад

      yeah its quite easy

    • @encrypteric2659
      @encrypteric2659 4 месяца назад

      ​@@yashshukla1637 so then why did you look up the video lmao shut up

    • @VarunMittal-viralmutant
      @VarunMittal-viralmutant 4 месяца назад +16

      @@yashshukla1637 Not quite. Modifying a binary search becomes tricky if one has not seen the question before, in my opinion

  • @sharan10salian
    @sharan10salian Год назад +108

    peak comment

  • @vasujhawar.6987
    @vasujhawar.6987 Год назад +25

    Thank you so much for building up the intution, I am going to buy lifetime Neetcode subscription, once I crack a job. You are the best instructor and teacher.💝💝

    • @manuelese8760
      @manuelese8760 2 месяца назад

      How much time did it take to build it?

  • @donotreportmebro
    @donotreportmebro Год назад +6

    if you calculate mid as int mid = left + (right - left) / 2, it's already a left biased mid (there an alternative approach to make mid right biased), in the case of left biased mid do (m + 1) instead of m - 1 to not worry about out of bounds on the left, left biased mid protects you from the out of bounds condition happening on the right

  • @NeetCodeIO
    @NeetCodeIO  Год назад +4

    If you're looking for todays daily LC (design browser history) 👉ruclips.net/video/i1G-kKnBu8k/видео.html

  • @harshalyallewar
    @harshalyallewar 5 месяцев назад +1

    00:03 Finding peak element in an array of integers.
    01:33 Determining peak element using binary search
    02:53 Modified binary search for finding peak element
    04:22 Identifying peak elements in binary search
    05:41 Monotonic sequence guarantees existence of peak element
    07:07 Identifying the peak element in a list using binary search algorithm.
    08:26 Calculating the Midway point to avoid overflow.
    09:48 Finding peak element using binary search in Python
    Crafted by Merlin AI.

  • @m.kamalali
    @m.kamalali Год назад +7

    we can simplify the code a little bit more
    l,r=0,len(nums)-1
    while l < r:
    mid = (l+r)//2
    if nums[mid]< nums[mid+1]:
    l=mid+1
    else:
    r=mid
    return r

    • @takerixgaming4170
      @takerixgaming4170 Год назад

      I can't understood bro

    • @vukanoa
      @vukanoa Год назад +7

      @@takerixgaming4170 Well, it's the same as Neet's, but there are three differences:
      1. He uses:
      *mid = (l+r)//2*
      instead of:
      *mid = left + ((right - left) / 2)*
      because he doesn't have to check for the overflow, as Neet himself noted as well. He just showed us this as a general good thing to know about a Binary Search.
      2. His first if statement is:
      *if (nums[mid] < nums[mid + 1])*
      instead of:
      *if (mid > 0 and nums[mid - 1])*
      because this way you don't have to check for "mid > 0" or "mid < len(nums) - 1". Why is this the case? Well, when calculating "mid" pointer at the beginning of the loop we're using an integer division. Meaning it's always "cut down". So we're sure that nums[mid + 1] will never be out of bounds.
      3. He doesn't have an "else" statement that breaks the loop, i.e. that returns "mid", instead his while loop breaks once left becomes greater than or equals to the right.
      Thus, at the end, out of the while loop, just return "left", since we're sure that is the answer.
      Run a Simulation or two on this code and you'll get it.
      I hope this helps.

  • @VarunMittal-viralmutant
    @VarunMittal-viralmutant 4 месяца назад

    Same approach, alternate code:
    def findPeak(nums):
    l , r = 0, len(nums)-1
    nums.append(-float('inf'))
    while l < r:
    m = (r + l)//2
    if nums[m+1] > nums[m]:
    l = m + 1
    else:
    r = m
    return l

  • @ngneerin
    @ngneerin Год назад +12

    Go mid
    If peak return
    If right is greater drop left
    If left is greater drop right
    Repeat

    • @kryptoknight992
      @kryptoknight992 10 месяцев назад +2

      what if both left and right element are grater than mid?

    • @ngneerin
      @ngneerin 10 месяцев назад +1

      @@kryptoknight992 Go any way depending on which side your program is checking. Both side there is at least 1 peak

  • @quirkyquester
    @quirkyquester 4 месяца назад

    beautiful explanation! Love it! Thank you! I was so confused, before watching the video!

  • @tanishkasharma8777
    @tanishkasharma8777 3 месяца назад

    dude best explanation so far

  • @jessanraj9086
    @jessanraj9086 Год назад +2

    Awesome explanation

  • @dusvn1484
    @dusvn1484 16 дней назад

    It's very simple question but I got stuck on point how to check this is index out of bounce. I made solution but it works only if peaks not edge element at index 0 and index len(array)-1. Very good trick to check is mid>0 when try to compare with mid-1 element. It helps me a lot.

  • @skairways
    @skairways 7 месяцев назад

    Great explanation, thanks

  • @krzym1
    @krzym1 6 месяцев назад +2

    I don't get the explanation at 9:29 if m==0 then it IS greater than its left neighbour as according to problem description the outOfBound element is -inf

    • @알바-r4l
      @알바-r4l 3 месяца назад

      I was initially confused by that too, but I think what he was just saying is “if mid is already the first element, is there a greater left element that requires us to update our right pointer?” The answer to that is no, we do not have a greater left element when mid is the first element, so don’t update our right pointer, so just return the mid index.

    • @알바-r4l
      @알바-r4l 3 месяца назад

      We can just return the mid index = 0 in this case because the fact that the current mid = 0 means: whatever the first element is, it is greater than the right neighbor and the “-inf” left neighbor

    • @gabrielfonseca1642
      @gabrielfonseca1642 19 дней назад

      I think he meant to say "if m == 0, is it SMALLER than a left neighbor" (i.e. is there a peak to the left of it? No)

    • @mohamedaminabdullahi
      @mohamedaminabdullahi 17 дней назад

      if m = 0, there is no m-1 to check, and if m=len(nums), there is no m+1 to check

  • @tazveerhossainkhan4856
    @tazveerhossainkhan4856 Год назад

    Great Explanation.

  • @its_shivam_jha
    @its_shivam_jha 7 месяцев назад

    thank you...built the intuition

  • @srinivasasowmiyan2272
    @srinivasasowmiyan2272 Год назад +2

    I don't know how you make it look pretty simple🙂

  • @davidnidam2378
    @davidnidam2378 2 месяца назад +1

    In binary search questions, within the while loop: When do we use '

    • @moobs
      @moobs Месяц назад

      if you return directly from a conditional check on the mid point you use

  • @mayilbayramov2886
    @mayilbayramov2886 Год назад

    Perfect explanation

  • @shivamsiddharthasinghrajaw7671
    @shivamsiddharthasinghrajaw7671 Год назад +9

    A greedy binary search if you will

  • @anujsingh-ej9vb
    @anujsingh-ej9vb 6 месяцев назад

    what if we are at a point and on both the sides we find numbers which are greater than the current number, then in that case, which side do we need to go with our Binary Search?

  • @user-le6ts6ci7h
    @user-le6ts6ci7h Год назад +1

    Whenever I solve this problem , "I am peaky blinder" is the song that comes into my mind

  • @calvinminnesota5540
    @calvinminnesota5540 Год назад

    Inspiring👍

  • @vikasgupta1828
    @vikasgupta1828 Год назад

    Thanks.

  • @jisanson
    @jisanson Год назад

    elegant 👍

  • @mayanksingh7814
    @mayanksingh7814 6 месяцев назад +1

    A simpler one:
    def findPeakElement(nums: List[int]):
    low, high = 0, len(nums)-1
    while low < high:
    mid = low + (high - low) //2
    if arr[mid+1] > arr[mid]:
    low = mid + 1
    else:
    high = mid
    return low

  • @ManishKumar-kw7qe
    @ManishKumar-kw7qe Месяц назад

    Thanks for saying "It is not that simple to come up"

  • @edwardteach2
    @edwardteach2 8 месяцев назад

    U a Peak God

  • @neiljohn2637
    @neiljohn2637 Год назад +1

    It won't work for when the list contains the same number throughout right? Coz this code will return m rather None.

  • @alisktl
    @alisktl Год назад +1

    I believe the problem cannot be solved in O(log n) time. For example, given the sequence [1, 2, 1, 2, 3, 4, 5, 7, 7], the correct answer should be 1. However, the solution with a time complexity of O(log n) would yield 7, which is incorrect.

    • @Pratik-tk6ts
      @Pratik-tk6ts Год назад +3

      no two neighbouring numbers are equal, check constraints

    • @alisktl
      @alisktl Год назад +1

      @Pratik-tk6ts thanks, did not see that constraint

  • @anonanon2625
    @anonanon2625 11 месяцев назад +1

    ruclips.net/video/HtSuA80QTyo/видео.html
    MITx 6.006 if you want a deeper understanding on Peak Finding. Professor Devadas also talks about 2D Peak Finding.

  • @aryansudan2239
    @aryansudan2239 Год назад

    what if it s a valley element i.e 1 2 1 2 3 with mid at the middle 1. Then both sides are equally applicable for binary search?????

    • @VictorNascimentoo
      @VictorNascimentoo Год назад +3

      You only need to guarantee the side you're looking for has a peak. You can return any peak, not the global max.

  • @donovanhood4696
    @donovanhood4696 Год назад

    You are literally the goat.

  • @callforpapers_
    @callforpapers_ 4 месяца назад +1

    the code doesnt seems right anymore, they chanaged the question ?

  • @Ben-se7vk
    @Ben-se7vk 4 месяца назад

    For some reason m = l + ((r - 1) // 2) wasn't passing all of the testcases. However, changing it to "m = (l+r) // 2" worked and passed all cases. Anybody got any explanations?

  • @evangelion933
    @evangelion933 Год назад +2

    I'm not sure I understand why there's always a peak. What would be the peak in the array [1, 2, 2, 1]? If the "peak" is directly next to an equal value, it's not strictly greater than it's neighbors, and if the values on the ends of the array aren't larger, is there actually a peak?

  • @erensolmaz2435
    @erensolmaz2435 6 месяцев назад

    I was thinking what if more than 1 peaks and how i could find all peaks with this solution. Then i read expl. It says any of the peaks. So we just need to get close to one peak and look for it index

  • @antonr786
    @antonr786 6 месяцев назад

    So basically we just guessing on which side we gonna have the peak?

  • @ghost_assassinz1877
    @ghost_assassinz1877 Год назад

    What would happen if you had [3,2,3,3]. Then the peak element would be on the left but both are greater than the 2 so how would you know?

  • @NiyoDilxwes
    @NiyoDilxwes 5 месяцев назад

    Python int don't overflow

  • @yuurishibuya4797
    @yuurishibuya4797 11 месяцев назад

    For binary search to work, the input must be sorted, is it sorted?
    I don’t see that in the requirements/constraints.
    I don’t see about repeated elements either.
    Such a crappy problem description.

    • @shamilgurban6439
      @shamilgurban6439 11 месяцев назад

      It is not sorted. And no, it doesn't have to be sorted unless you are searching for an element in an array. Binary search is more about taking the middle of array and ignoring other side. So in this problem when we take mid element and we see that right side is less but left side is greater we go to left. Peak might be in right side too but it is not guaranteed because it can monotonically decrease. How about left side ? Either this monotonically increases or it goes down and both case is acceptable so we just ignore the right side. Binary search is much more than finding element in sorted array.

    • @adityapratapsinghtomer3624
      @adityapratapsinghtomer3624 6 месяцев назад

      @@shamilgurban6439 Legend !! Thanks man

  • @andhikaagung2936
    @andhikaagung2936 Год назад

    My solution to this problem actually by searching the maximal value of an array then return the index of that value. If using python we just need to call max and using index() method

    • @xrobstar
      @xrobstar Год назад +3

      The question states that an O(log n) solution is required. Searching for the max element is a linear O(n) solution.

  • @boyuanchang8708
    @boyuanchang8708 Месяц назад

    Will you merry me just say yes.

  • @DeathSugar
    @DeathSugar Год назад +2

    you need a better font or stop using one letter variables. I've got a time limits because it turned into an infinite loop because i put 1 instead of L in the middle point equation

    • @DinujayaRajakaruna
      @DinujayaRajakaruna Год назад +13

      I mean that error is easy to spot if you understood his explanation. The point of the video isn't for the viewers to copy his code, its for them to understand the explanation.

    • @DeathSugar
      @DeathSugar Год назад +1

      @@DinujayaRajakaruna i used another language and wasted a bunch of minutes becaise of it. i understand that leetcode is not about good code, but fast one, but still why not to improve to the sane degree?

    • @DinujayaRajakaruna
      @DinujayaRajakaruna Год назад

      @@DeathSugar While I do agree making things more readable helps in general, I think someone that is familiar with binary search will immediately understand what things like "r" and "l" stand for. Especially after he mentions what they are in the video.

    • @DeathSugar
      @DeathSugar Год назад

      @@DinujayaRajakaruna problem not with understaning. It uses "magic" evaluation to prevent from violating boundries - thats where I messed up with the 1/l.

    • @DinujayaRajakaruna
      @DinujayaRajakaruna Год назад

      @@DeathSugar it's not "magic" though, m = l + floor((r-l)/2) is exactly how you calculate the midpoint of l and r without getting any overflow issues. The standard way is m = floor((l+r)/2) but if l and r are large enough this overflows. He mentions this in the video, and this fact is mentioned in the Wikipedia page for binary search as well.

  • @ISHASARDA
    @ISHASARDA 8 дней назад

    great explanation