Skip to content

Commit

Permalink
Added solution 311
Browse files Browse the repository at this point in the history
  • Loading branch information
WHAHA-HA committed Sep 26, 2020
1 parent f0aadf4 commit 5dea68d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Problems/311.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PROBLEM 311:

Given an unsorted array, in which all elements are distinct, find a "peak" element in O(log N) time.

An element is considered a peak if it is greater than both its left and right neighbors. It is guaranteed that the first and last elements are lower than all others.
45 changes: 45 additions & 0 deletions Solutions/311.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""
Problem:
Given an unsorted array, in which all elements are distinct, find a "peak" element in
O(log N) time.
An element is considered a peak if it is greater than both its left and right
neighbors. It is guaranteed that the first and last elements are lower than all others.
"""

from typing import List


def get_peak(arr: List[int]) -> int:
# implement similar method as binary search [since the element being searched is
# not a concrete value (unlike binary search), but any value which is greater than
# its neighbours, it can only be found without sorting]
mid = len(arr) // 2
if (
mid > 0
and arr[mid - 1] < arr[mid]
and mid < len(arr)
and arr[mid + 1] < arr[mid]
):
return arr[mid]
elif mid > 0 and arr[mid - 1] < arr[mid]:
return get_peak(arr[mid:])
return get_peak(arr[: mid + 1])


if __name__ == "__main__":
print(get_peak([0, 2, 4, -1, 3, 1]))
print(get_peak([0, 2, 4, 5, 3, 1]))
print(get_peak([0, 2, 6, 5, 3, 1]))
print(get_peak([0, 2, 4, 5, 7, 1]))
print(get_peak([0, 8, 7, 5, 16, 1]))


"""
SPECS:
TIME COMPLEXITY: O(log(n))
SPACE COMPLEXITY: O(1)
"""

0 comments on commit 5dea68d

Please sign in to comment.