O(n) time and O(n) memory, instead of O(n²) with two loops.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # ====================================================================== # Q: Find two products whose prices add up exactly to a budget (two-sum). # # O(n) time and O(n) memory, instead of O(n²) with two loops. For money I work # with integer cents. # ====================================================================== def two_sum(prices: list[int], budget: int) -> tuple[int, int] | None: seen = {} # price -> index for i, p in enumerate(prices): if budget - p in seen: return seen[budget - p], i seen[p] = i return None |