|
| 1 | +# 315. Count of Smaller Numbers After Self |
| 2 | +# 🔴 Hard |
| 3 | +# |
| 4 | +# https://leetcode.com/problems/count-of-smaller-numbers-after-self/ |
| 5 | +# |
| 6 | +# Tags: Array - Binary Search - Divide and Conquer - Binary Indexed Tree - Segment Tree - Merge Sort - Ordered Set |
| 7 | + |
| 8 | +import timeit |
| 9 | +from typing import List |
| 10 | + |
| 11 | + |
| 12 | +# We can start by the naive brute-force solution, visit each number in nums in order and check how many |
| 13 | +# elements after nums are smaller than it. O(n2) - it will fail with Time Limit Exceeded. |
| 14 | +# |
| 15 | +# Time complexity: O(n^2). |
| 16 | +# Space complexity: O(1) - if we don't take into account the input and output arrays. |
| 17 | +class Naive: |
| 18 | + def countSmaller(self, nums: List[int]) -> List[int]: |
| 19 | + res = [0] * len(nums) |
| 20 | + for i, num in enumerate(nums): |
| 21 | + for val in nums[i + 1 :]: |
| 22 | + if val < num: |
| 23 | + res[i] += 1 |
| 24 | + return res |
| 25 | + |
| 26 | + |
| 27 | +# A specialized binary indexed tree where the update method only increments by 1. |
| 28 | +# There is an example of a standard binary indexed tree with comments in `utils/binary_indexed_tree.py` |
| 29 | +class BITree: |
| 30 | + def __init__(self, n: int): |
| 31 | + self.sums = [0] * (n + 1) |
| 32 | + |
| 33 | + def update(self, idx: int) -> None: |
| 34 | + idx += 1 |
| 35 | + while idx < len(self.sums): |
| 36 | + self.sums[idx] += 1 |
| 37 | + idx += idx & -idx |
| 38 | + |
| 39 | + def sum(self, idx: int) -> int: |
| 40 | + res = 0 |
| 41 | + while idx > 0: |
| 42 | + res += self.sums[idx] |
| 43 | + idx -= idx & -idx |
| 44 | + return res |
| 45 | + |
| 46 | + |
| 47 | +# Use a binary indexed tree to keep count, for each value in the input array, of how many elements equal or smaller |
| 48 | +# we have already seen. Then start iterating from the back of the input array, for each position, update the result |
| 49 | +# array and add the current value to the binary indexed tree. |
| 50 | +# |
| 51 | +# Time complexity: O(n*log(n)) - We visit each element on the input array and, for each, update the tree O(log(n)). |
| 52 | +# Space complexity: O(n) - The binary indexed tree is stored in memory as an array of size len(nums) + 1. |
| 53 | +# |
| 54 | +# Runtime: 4187 ms, faster than 54.52% of Python3 online submissions for Count of Smaller Numbers After Self. |
| 55 | +# Memory Usage: 34.8 MB, less than 51.30% of Python3 online submissions for Count of Smaller Numbers After Self. |
| 56 | +class BITSolution: |
| 57 | + def countSmaller(self, nums): |
| 58 | + |
| 59 | + # Create a dictionary of all unique values in the input array as keys pointing to their |
| 60 | + # position if they were an ordered set with the smallest at 0 and the biggest at len(n) - 1. |
| 61 | + dict = {value: idx for idx, value in enumerate(sorted(set(nums)))} |
| 62 | + |
| 63 | + # Initialize the binary indexed tree, and the results array, to all 0s |
| 64 | + bi_tree, res = BITree(len(dict)), [0] * len(nums) |
| 65 | + |
| 66 | + # Start at the back of nums and iterate over every position |
| 67 | + for i in range(len(nums) - 1, -1, -1): |
| 68 | + |
| 69 | + # Update the result set with the current sum of frequencies in the tree at that point. |
| 70 | + # The tree contains, for each value, the sum of elements smaller than the current one. |
| 71 | + res[i] = bi_tree.sum(dict[nums[i]]) |
| 72 | + |
| 73 | + # Update the sums on the binary indexed tree. This is a special use case in which we always increment |
| 74 | + # by 1 and we are using the dictionary to translate between values and indexes. |
| 75 | + # The result is that increasing the value at the index pointed to by the dictionary, we increase the |
| 76 | + # numbers equal or less than this value that we have seen up to that moment. |
| 77 | + # Since we are iterating from the back, we can use that information to check how many values less than |
| 78 | + # the current one we have seen and update the result array. |
| 79 | + bi_tree.update(dict[nums[i]]) |
| 80 | + |
| 81 | + return res |
| 82 | + |
| 83 | + |
| 84 | +# TODO look into the segment tree solution. |
| 85 | +# https://www.topcoder.com/thrive/articles/Range%20Minimum%20Query%20and%20Lowest%20Common%20Ancestor |
| 86 | +class SegmentTreeSol: |
| 87 | + def countSmaller(self, nums: List[int]) -> List[int]: |
| 88 | + pass |
| 89 | + |
| 90 | + |
| 91 | +# TODO look into the merge sort solution. |
| 92 | +class MergeSortSol: |
| 93 | + def countSmaller(self, nums: List[int]) -> List[int]: |
| 94 | + pass |
| 95 | + |
| 96 | + |
| 97 | +def test(): |
| 98 | + executors = [ |
| 99 | + # Naive, |
| 100 | + BITSolution, |
| 101 | + ] |
| 102 | + tests = [ |
| 103 | + [ |
| 104 | + [3, 10, 0, 7, 1, -13, 6, -5, 16, 7, 3, -9], |
| 105 | + [5, 9, 3, 6, 3, 0, 3, 1, 3, 2, 1, 0], |
| 106 | + ], |
| 107 | + [[5, 2, 6, 1], [2, 1, 1, 0]], |
| 108 | + [[-1], [0]], |
| 109 | + [[-1, -1], [0, 0]], |
| 110 | + ] |
| 111 | + for executor in executors: |
| 112 | + start = timeit.default_timer() |
| 113 | + for _ in range(int(float("1"))): |
| 114 | + for col, t in enumerate(tests): |
| 115 | + sol = executor() |
| 116 | + result = sol.countSmaller(t[0]) |
| 117 | + exp = t[1] |
| 118 | + assert ( |
| 119 | + result == exp |
| 120 | + ), f"\033[93m» {result} <> {exp}\033[91m for test {col} using \033[1m{executor.__name__}" |
| 121 | + stop = timeit.default_timer() |
| 122 | + used = str(round(stop - start, 5)) |
| 123 | + res = "{0:20}{1:10}{2:10}".format(executor.__name__, used, "seconds") |
| 124 | + print(f"\033[92m» {res}\033[0m") |
| 125 | + |
| 126 | + |
| 127 | +test() |
0 commit comments