src.two_sum

Classes

Solution()

class src.two_sum.Solution[source][source]
twoSum(nums: list[int], target: int) list[int][source]

Thought process

  • We create a dictionary to store value -> index

  • We recognize the property a + b = target -> target - a = b -> ans = [idx(target - a), idx(a)]

  • Since we now only need the current element and target, we can simply:

  • iterate through the list

  • compute the difference

  • see if the difference is in the dictionary

Notes

  • time complexity: O(n)

  • space complexity: O(n)