I have a quick question about the below code regarding hash tables. For line 5- what is happening? So we initialised 'hash_table' to be a dictionary. Then for each element 'i' in nums we do hash_table[i]?? But the hash_table is empty- since just initialised it? This is where I am confused. Is it correct to say that we are defining the keys by doing hash_table['i']? If this is the case, why +=1? (P.S. nums is a list of integers shall we say)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
hash_table = defaultdict(int)
for i in nums:
hash_table[i] += 1
for i in hash_table:
if hash_table[i] == 1:
return i
I think your understanding of the defaultdict
is correct: If the key is not present, then the key will be added with a default value. In the case of a defaultdict(int)
, that default value will be 0. But what are you passing as nums
? If nums
is not empty then hash_table
will not be empty after the first for
loop. However, method singleNumber
just returns a single value, which will be the first key of hash_table
that appeared in the nums
list only once. As Tomericlo pointed out, your hash_table
is acting more like a set of counters counting the number of times that each distinct integer in nums
appears. I have modified your code to insert a print
statement (and missing import
statements) and added a test case.
Note that if no integer in nums
appears only once, then your code never finds a match and never issues a return
statement, which is equivalent to returning the value None
.
from collections import defaultdict
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
hash_table = defaultdict(int)
for i in nums:
hash_table[i] += 1
print(hash_table) # added statement
for i in hash_table:
if hash_table[i] == 1:
return i
# test case:
solution = Solution()
print(solution.singleNumber([7, 6, 7, 12]))
Prints:
defaultdict(<class 'int'>, {7: 2, 6: 1, 12: 1})
6