File: two-sum-iii-data-structure-design/solution.py

Date: 2026-06-06

Time: 19:33

Purpose

This file implements LeetCode problem 170 - Two Sum III (Data Structure Design). It provides a class that supports two operations: adding numbers to a multiset, and querying whether any pair of previously-added numbers sums to a given target. It's the streaming/online variant of the classic Two Sum problem — instead of a fixed array, numbers arrive incrementally.

Key Components

TwoSum class

A stateful data structure with two methods:

Returns True on first match, False after exhausting all keys. O(n) where n is the number of distinct values.

Patterns

Hash-based complement lookup — the same pattern as classic Two Sum, but adapted for a streaming context. Instead of building a set during a single pass over a fixed array, the Counter accumulates state across multiple add calls.

Self-pairing guard — the complement != num branch prevents a number from pairing with itself unless it was added at least twice. This is the critical subtlety in the problem; without the count check, add(3); find(6) would incorrectly return True.

Dependencies

Flow

1. Client creates a TwoSum() instance.

2. Client calls add(n) repeatedly — each call is a single Counter increment.

3. Client calls find(value) — the method performs a linear scan over the keys of counts, computing the complement for each and checking existence/count. Short-circuits on first hit.

Invariants

Error Handling

None. The class assumes valid integer inputs per the LeetCode contract. No bounds checking, no exception handling. Counter._getitem_ returns 0 for missing keys, so the complement in self.counts check is the only guard needed.

Topics to Explore

Beliefs