This problem requires designing a data structure that efficiently handles adding numbers and checking if any pair of numbers in the structure sums up to a target value. The optimal approach uses a hash table (or dictionary) to store the frequency of each number.
Approach:
Data Structure: A hash table (like HashMap
in Java, Dictionary
in C#, unordered_map
in C++, dict
in Python, Map
in TypeScript, or map
in Go) is the most efficient data structure for this task. The keys of the hash table represent the numbers, and the values represent their counts.
add(number)
: This method simply adds a given number
to the hash table. If the number
already exists, its count is incremented; otherwise, it's added with a count of 1. This operation has a time complexity of O(1) on average (due to hash table's constant-time average lookup, insertion, and deletion).
find(value)
: This method checks if there exists a pair of numbers in the hash table that sum up to the given value
. The algorithm iterates through the hash table. For each number x
, it checks if value - x
(let's call it y
) also exists in the hash table:
If y
exists and x != y
: This means we've found a distinct pair (x
, y
) that sums to value
, so we return true
.
If y
exists and x == y
: In this case, we need to check if the count of x
is greater than 1 (meaning we have at least two instances of the same number). If the count is greater than 1, we return true
; otherwise, we continue searching.
If y
doesn't exist: We continue to the next number in the hash table.
If the loop completes without finding a suitable pair, it means no such pair exists, and we return false
. The time complexity of this method is O(n) in the worst case, where n is the number of unique numbers in the hash table.
Time and Space Complexity:
Time Complexity:
add(number)
: O(1) on average (hash table operations)find(value)
: O(n) in the worst case (iterating through the hash table)Space Complexity: O(n), where n is the number of unique numbers added to the data structure. This is because the hash table stores the unique numbers and their frequencies.
Code Examples (with explanations inline):
The code examples provided in the previous response demonstrate this approach in various programming languages. Each example follows the same algorithmic structure: a hash table is used to store number frequencies, add()
increments counts, and find()
efficiently searches for pairs. The minor differences between the languages reflect their syntax and standard library implementations of hash tables. For example, in Python, defaultdict(int)
is used to avoid explicit checks for key existence before incrementing counts. In Java, Map.merge()
provides a concise way to update counts, and so on. All the implementations adhere to the described algorithm and complexity.