Solution: Two Sum III - Data structure design
Let's solve the Two Sum III - Data structure design problem using the Custom Data Structures pattern.
We'll cover the following
Statement
Design a data structure that takes in a stream of numbers and can check if any two numbers add up to a specific value.
Implement the TwoSum
class with the following constructor and methods:
Constructor: Sets up the
TwoSum
object with an empty list at the start.void add(int number): Adds a new number to the list.
boolean find(int value): Returns TRUE if any two numbers in the list add up to the given value. If not, it returns FALSE.
Constraints:
number
value
At most,Â
 calls will be made to add and find methods.
Solution
The algorithm uses a custom data structure to solve this problem efficiently. The idea is to use a hash map to store the numbers and their frequencies as we iterate over the array. This custom data structure will allow us to quickly look up and manage the frequencies of the numbers. Using the frequency data, we can quickly identify whether the required pair of numbers or sufficient occurrences of a single number are present to achieve the target sum.
We will iterate over the numbers array and put each number in the hash map with the frequency of
The algorithm to solve this problem is as follows:
Create a class and initialize an instance of the hash map in its constructor. Moreover, implement two methods in the class: add(number) and find(target).
add(number) method. If a
number
is not already in the hash map, put thatnumber
in the hash map as a key andas a value. If the number
is already in the hash map, increase thatnumber
's value (frequency) by. find(target) method. Iterate over the keys of the hash map. For each key, calculate the difference as
target - key
.If the difference is not equal to the
key
, check if the hash map has another key equal to the difference; if so, it means we have found two numbers equal totarget
and will returntrue
.If the difference is equal to the
key
, check if the frequency ofkey
is at least two. If so, we have found two numbers equal to the target and will returntrue
.In either case, if no two numbers sum up to
target
, we will returnfalse
.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.