Two Sum III – Data structure design – Python 3 (Week 14 – 17)

class TwoSum:
    
    def __init__(self):
        self.counter = {}
    """
    @param number: An integer
    @return: nothing
    """
    def add(self, number):
        # write your code here
        self.counter[number] = self.counter.get(number, 0) + 1
        #O(1)
    """
    @param value: An integer
    @return: Find if there exists any pair of numbers which sum is equal to the value.
    """
    def find(self, value):
        # write your code here
        #O(n)
        for key in self.counter:
            if value - key in self.counter and value != key *2:
                return True
            if value == key * 2 and self.counter[key] >= 2:
                return True
        
        return False

Leave a comment

Design a site like this with WordPress.com
Get started