[Python] Trouble finding peak in mountain-like array with duplicates — binary search not...

Discussão em 'Python' iniciado por Stack, Junho 29, 2025.

  1. Stack

    Stack Membro Participativo

    `I'm trying to solve a problem where I need to find the peak element in a mountain-like array that may contain duplicates.

    A peak element is one where the values first increase and then decrease (but plateaus like [6,6,6,6] may appear after the peak). Here's the code I’ve written:`

    nums = [1, 3, 7, 6, 6, 6, 6, 6, 4, 3, 2, 1]

    l = 0
    r = len(nums) - 1

    while l < r:
    # Skip duplicates on the left
    while l < r and nums[l] == nums[l + 1]:
    l += 1
    # Skip duplicates on the right
    while l < r and nums[r] == nums[r - 1]:
    r -= 1

    m = (l + r) // 2

    if nums[m] < nums[m + 1]:
    l = m + 1
    else:
    r = m

    print(nums[l]) # Expected output: 7


    For the input:

    [1, 3, 7, 6, 6, 6, 6, 6, 4, 3, 2, 1]


    `I expect the peak to be 7, but the output is coming out as 6.

    I suspect it’s due to the plateau confusing the binary search logic. How can I correctly handle duplicates, especially when there’s a long flat section after the peak?

    Any suggestions on improving the binary search logic to correctly identify the peak in such cases would be really helpful.`

    Continue reading...

Compartilhe esta Página