GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Arrays/find_peak_element.py at master · vipkolon/coding-problems

Expand file tree

/

find_peak_element.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
56 lines (43 loc) · 1.59 KB
/

find_peak_element.py

Copy path

File metadata and controls

56 lines (43 loc) · 1.59 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'''
Find Peak Element
A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
Input: [1, 2, 3, 1]
Output: 2
Output explanation: 3 is a peak element and your function should return the index number 2.
Input: [1, 2, 1, 3, 5, 6, 4]
Output: 1 or 5
Output explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
=========================================
Binary search (more description in the code).
Time Complexity: O(LogN)
Space Complexity: O(1)
'''
############
# Solution #
############
def find_peak_element(nums):
l = 0
r = len(nums) - 1
while l < r:
mid = (l + r) // 2
if nums[mid] > nums[mid + 1]:
# go left if the current value is smaller than the next one
# in this moment you're sure that there is a peak element left from this one
r = mid
else:
# go right if the current value is smaller than the next one
# if the l comes to the end and all elements were in ascending order, then the last one is peak (because nums[n] is negative infinity)
l = mid + 1
return l
###########
# Testing #
###########
# Test 1
# Correct result => 2
print(find_peak_element([1, 2, 3, 1]))
# Test 2
# Correct result => 1 or 5
print(find_peak_element([1, 2, 1, 3, 5, 6, 4]))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.