From 5dea68d75eac7ab4d8382cc25dd68155e6d8cf2c Mon Sep 17 00:00:00 2001 From: WHAHA-HA Date: Sat, 26 Sep 2020 08:56:07 +0530 Subject: [PATCH] Added solution 311 --- Problems/311.txt | 5 +++++ Solutions/311.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 Problems/311.txt create mode 100644 Solutions/311.py diff --git a/Problems/311.txt b/Problems/311.txt new file mode 100644 index 0000000..ed26f6d --- /dev/null +++ b/Problems/311.txt @@ -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. \ No newline at end of file diff --git a/Solutions/311.py b/Solutions/311.py new file mode 100644 index 0000000..435306a --- /dev/null +++ b/Solutions/311.py @@ -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) +""" +