|
2 | 2 |
|
3 | 3 | from test_framework import generic_test
|
4 | 4 |
|
| 5 | +""" |
| 6 | +Smallest case would be like: |
| 7 | +k = 3: 0 1 0 | 1 0 | 1 0 |
5 | 8 |
|
6 |
| -def sort_k_increasing_decreasing_array(A: List[int]) -> List[int]: |
7 |
| - # TODO - you fill in here. |
8 |
| - return [] |
| 9 | +brute force sort is nlogn, can ideally do better |
| 10 | +vals could be pos, neg, or zero |
| 11 | +
|
| 12 | +""" |
| 13 | +import heapq |
| 14 | +import collections |
| 15 | + |
| 16 | +subarray = collections.namedtuple("subarray", ["val", "left", "right", "increasing"]) |
| 17 | + |
| 18 | + |
| 19 | +def get_subarrays(arr): |
| 20 | + if not arr or (len(arr) == 1): |
| 21 | + return [arr] |
| 22 | + subarrays = [] |
| 23 | + curr = [] |
| 24 | + increasing = arr[0] < arr[1] |
| 25 | + i = 0 |
| 26 | + while i < len(arr)-1: |
| 27 | + if ((arr[i] < arr[i+1]) and not increasing) or ((arr[i] > arr[i+1]) and increasing): |
| 28 | + subarrays.append(curr if increasing else curr[::-1]) |
| 29 | + curr = [] |
| 30 | + increasing = not increasing |
| 31 | + curr.append(arr[i]) |
| 32 | + i += 1 |
| 33 | + |
| 34 | + if not curr: |
| 35 | + subarrays.append([arr[i]]) |
| 36 | + else: |
| 37 | + curr.append(arr[i]) |
| 38 | + subarrays.append(curr if increasing else curr[::-1]) |
| 39 | + return subarrays |
| 40 | + |
| 41 | + |
| 42 | +def sort_k_increasing_decreasing_array(array: List[int]) -> List[int]: |
| 43 | + subarrs = get_subarrays(array) |
| 44 | + heap = [(arr[0], 0, i) for i, arr in enumerate(subarrs)] |
| 45 | + heapq.heapify(heap) |
| 46 | + merged = [] |
| 47 | + while heap: |
| 48 | + val, idx, arr_id = heapq.heappop(heap) |
| 49 | + merged.append(val) |
| 50 | + new_idx = idx+1 |
| 51 | + parent_arr = subarrs[arr_id] |
| 52 | + if new_idx < len(parent_arr): |
| 53 | + heapq.heappush(heap, (parent_arr[new_idx], new_idx, arr_id)) |
| 54 | + |
| 55 | + return merged |
9 | 56 |
|
10 | 57 |
|
11 | 58 | if __name__ == '__main__':
|
| 59 | + cases = [ |
| 60 | + # [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5], |
| 61 | + # [1, 2, 3, 2, 1, 4, 5, 10, 9, 4, 4, 1, -1], |
| 62 | + # [1, 2, 4, 4, 5, 1, 2, 3, 4, 5, -10, 10, -10], |
| 63 | + [2147483647, 8, 4, 2, 1, 0, -1, -2147483648] |
| 64 | + ] |
| 65 | + for case in cases: |
| 66 | + # print(get_subarrays(case)) |
| 67 | + expected = sorted(case) |
| 68 | + actual = sort_k_increasing_decreasing_array(case) |
| 69 | + assert actual == expected, f"\ncase: {case}\n{actual} != {expected}" |
12 | 70 | exit(
|
13 | 71 | generic_test.generic_test_main('sort_increasing_decreasing_array.py',
|
14 | 72 | 'sort_increasing_decreasing_array.tsv',
|
|
0 commit comments