-
Notifications
You must be signed in to change notification settings - Fork 40
/
peaks_and_valleys_O_nlogn.py
58 lines (50 loc) · 1.58 KB
/
peaks_and_valleys_O_nlogn.py
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
57
58
# Date: 2018-07-26
#
# Description:
# In an array of integers, a "peak" is an element which is greater than or equal
# to the adjacent integers and a "valley" is an element which is less than or
# equal to the adjacent integers.
# For example, in the array {5, 8, 6, 2, 3, 4, 6 }, {8, 6} are peaks and {5, 2}
# are valleys. Given an array of integers, sort the array into an alternating
# sequence of peaks and valleys.
# EXAMPLE
# Input: {5, 3, 1, 2, 3}
# Output: {5, 1, 3, 2, 3}
#
# Approach:
# Sort the array in ascending order then swap adjacent elements since every
# three elements appear in the order small <= medium <= large, swapping these
# elements will always put medium as a peak and small as valley:
# medium <= small <= large.
#
# Complexity:
# O(nlogn)
def getPeaksAndValleys(a, n):
idx = 1
# Sort a in ascending order, O(nlogn) operation.
a.sort()
while idx < n:
a[idx - 1], a[idx] = a[idx], a[idx - 1] # Swap adjacent elements.
idx += 2
return a
def main():
arr = [5, 3, 1, 2, 3]
print(f'Input: {arr}')
print('Peak valley pattern:', getPeaksAndValleys(arr, len(arr)))
arr = [10, 5, 2, 3, 9, 8, 7, 6, 1, 4]
print(f'Input: {arr}')
print('Peak valley pattern:', getPeaksAndValleys(arr, len(arr)))
arr = [5, 10]
print(f'Input: {arr}')
print('Peak valley pattern:', getPeaksAndValleys(arr, len(arr)))
if __name__ == '__main__':
main()
# Output:
# Input: [5, 3, 1, 2, 3]
# Peak valley pattern: [5, 2, 3, 1, 3]
#
# Input: [10, 5, 2, 3, 9, 8, 7, 6, 1, 4]
# Peak valley pattern: [10, 2, 3, 1, 5, 4, 7, 6, 9, 8]
#
# Input: [5, 10]
# Peak valley pattern: [10, 5]