KatInterview

170. Two Sum III - Data structure design

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires designing a data structure that supports two main operations: adding an integer to a collection and determining if any two integers in that collection sum up to a specific target value. The core of the problem is to choose an internal storage mechanism that provides an efficient trade-off for the time complexities of the add and find operations, considering they can be interleaved and called many times.

Solution

Two Sum III - Data structure design in Python

class TwoSum:

    def __init__(self):
        self.freq_map = {}

    def add(self, number: int) -> None:
        # Increment the frequency count of the number.
        self.freq_map[number] = self.freq_map.get(number, 0) + 1

    def find(self, value: int) -> bool:
        # Iterate through the keys in the frequency map.
        for num1 in self.freq_map:
            complement = value - num1
            
            # Case 1: The complement is the same as the current number.
            if complement == num1:
                # We need at least two instances of this number.
                if self.freq_map[num1] > 1:
                    return True
            # Case 2: The complement is a different number.
            else:
                # We need to check if the complement exists in our map.
                if complement in self.freq_map:
                    return True
        return False


# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value)

Two Sum III - Data structure design in Java

import java.util.HashMap;
import java.util.Map;

class TwoSum {
    private Map<Long, Integer> freqMap;

    public TwoSum() {
        this.freqMap = new HashMap<>();
    }
    
    public void add(int number) {
        // Use long for keys to avoid overflow issues with complements and for consistency.
        long longNumber = number;
        this.freqMap.put(longNumber, this.freqMap.getOrDefault(longNumber, 0) + 1);
    }
    
    public boolean find(int value) {
        // Iterate through the key-value pairs in the map.
        for (Map.Entry<Long, Integer> entry : this.freqMap.entrySet()) {
            long num1 = entry.getKey();
            int count = entry.getValue();
            // Calculate complement. All values are long, so no overflow issues here.
            long complement = (long)value - num1;
            
            // Case 1: The complement is the same as the current number.
            if (complement == num1) {
                // We need at least two instances of this number.
                if (count > 1) {
                    return true;
                }
            } 
            // Case 2: The complement is a different number.
            else {
                // We need to check if the complement exists in our map.
                if (this.freqMap.containsKey(complement)) {
                    return true;
                }
            }
        }
        return false;
    }
}

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * boolean param_2 = obj.find(value);
 */

Two Sum III - Data structure design in C++

#include <unordered_map>

class TwoSum {
private:
    // Use long long for keys to avoid overflow issues when calculating complements.
    std::unordered_map<long long, int> freqMap;

public:
    TwoSum() {
        // The map is default-initialized.
    }
    
    void add(int number) {
        // Increment the frequency count of the number.
        // 'number' is promoted to long long when used as a key.
        freqMap[number]++;
    }
    
    bool find(int value) {
        // Iterate through the key-value pairs in the map.
        for (auto const& [num, count] : freqMap) {
            // Calculate complement using long long to prevent overflow.
            long long complement = (long long)value - num;
            
            // Case 1: The complement is the same as the current number.
            // We need at least two instances of this number.
            if (complement == num) {
                if (count > 1) {
                    return true;
                }
            } 
            // Case 2: The complement is a different number.
            // We need to check if the complement exists in our map.
            else {
                if (freqMap.count(complement)) {
                    return true;
                }
            }
        }
        return false;
    }
};

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum* obj = new TwoSum();
 * obj->add(number);
 * bool param_2 = obj->find(value);
 */

Two Sum III - Data structure design in TypeScript

class TwoSum {
    private freqMap: Map<number, number>;

    constructor() {
        this.freqMap = new Map();
    }

    add(number: number): void {
        // Get the current count, or 0 if not present, then increment and put it back.
        const count = this.freqMap.get(number) || 0;
        this.freqMap.set(number, count + 1);
    }

    find(value: number): boolean {
        // Iterate through the key-value pairs in the map.
        // TypeScript's 'number' type is 64-bit float, which can safely handle
        // the given integer constraints without overflow.
        for (const [num1, count] of this.freqMap.entries()) {
            const complement = value - num1;
            
            // Case 1: The complement is the same as the current number.
            if (complement === num1) {
                // We need at least two instances of this number.
                if (count > 1) {
                    return true;
                }
            } 
            // Case 2: The complement is a different number.
            else {
                // We need to check if the complement exists in our map.
                if (this.freqMap.has(complement)) {
                    return true;
                }
            }
        }
        return false;
    }
}

/**
 * Your TwoSum object will be instantiated and called as such:
 * var obj = new TwoSum()
 * obj.add(number)
 * var param_2 = obj.find(value)
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.