|
| 1 | +# Three Number Sum |
| 2 | +# 🟠 Medium |
| 3 | +# |
| 4 | +# https://www.algoexpert.io/questions/three-number-sum |
| 5 | +# |
| 6 | +# Tags: Array, Two Pointer, Sorting |
| 7 | + |
| 8 | +import timeit |
| 9 | + |
| 10 | + |
| 11 | +# Find all combinations of three numbers in the input that add up to the |
| 12 | +# target sum by fixing one number at a time and using two pointers to |
| 13 | +# find combinations of other two numbers that make up to the sum. |
| 14 | +# |
| 15 | +# Time complexity: O(n^2) - For each value in the array, we explore all |
| 16 | +# combinations of other two values in linear time. |
| 17 | +# Space complexity: O(1) - If we don't count the output or input arrays. |
| 18 | +class Solution: |
| 19 | + def threeNumberSum(self, array, targetSum): |
| 20 | + array.sort() |
| 21 | + res = [] |
| 22 | + # Fix the leftmost element, then use two pointers to find all |
| 23 | + # combinations of other two values that add to the target sum. |
| 24 | + for i in range(len(array) - 2): |
| 25 | + l, r = i + 1, len(array) - 1 |
| 26 | + while l < r: |
| 27 | + val = array[i] + array[l] + array[r] |
| 28 | + if val == targetSum: |
| 29 | + res.append((array[i], array[l], array[r])) |
| 30 | + l += 1 |
| 31 | + r -= 1 |
| 32 | + elif val < targetSum: |
| 33 | + l += 1 |
| 34 | + else: |
| 35 | + r -= 1 |
| 36 | + return res |
| 37 | + |
| 38 | + |
| 39 | +def test(): |
| 40 | + executors = [ |
| 41 | + Solution, |
| 42 | + ] |
| 43 | + tests = [ |
| 44 | + [[8, 10, -2, 49, 14], 57, [(-2, 10, 49)]], |
| 45 | + [[1, 2, 3, 4, 5, 6, 7, 8, 9, 15], 29, [(5, 9, 15), (6, 8, 15)]], |
| 46 | + [[12, 3, 1, 2, -6, 5, -8, 6], 0, [(-8, 2, 6), (-8, 3, 5), (-6, 1, 5)]], |
| 47 | + ] |
| 48 | + for executor in executors: |
| 49 | + start = timeit.default_timer() |
| 50 | + for _ in range(1): |
| 51 | + for col, t in enumerate(tests): |
| 52 | + sol = executor() |
| 53 | + result = sol.threeNumberSum(t[0], t[1]) |
| 54 | + exp = t[2] |
| 55 | + assert result == exp, ( |
| 56 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 57 | + + f" test {col} using \033[1m{executor.__name__}" |
| 58 | + ) |
| 59 | + stop = timeit.default_timer() |
| 60 | + used = str(round(stop - start, 5)) |
| 61 | + cols = "{0:20}{1:10}{2:10}" |
| 62 | + res = cols.format(executor.__name__, used, "seconds") |
| 63 | + print(f"\033[92m» {res}\033[0m") |
| 64 | + |
| 65 | + |
| 66 | +test() |
0 commit comments