Skip to content

Two Sum

from typing import List


def twoSum(nums: List[int], target: int) -> List[int]:
    num_index = {}
    for index, num in enumerate(nums):
        if target - num in num_index:
            return [index, num_index[target - num]]
        num_index[num] = index


nums = [2,7,11,15]
target = 9

twoSum(nums, target)
[1, 0]
# 08/03/26
# Input: nums = [2,7,11,15], target = 9
# Output: [0,1]
# Input: nums = [3,2,4], target = 6
# Output: [1,2]
# Input: nums = [3,3], target = 6
# Output: [0,1]
from typing import List

def twoSum(nums: List[int], target: int) -> List[int]:
    num_index = {}

    for index in range(len(nums)):
        num_index[nums[index]] = index
    for index in range(len(nums)):
        complement = target - nums[index]
        if complement in num_index and num_index[complement] != index:
            return [index, num_index[complement]]
    return []


checks = [([2,7,11,15], 9, [0,1]), ([3,2,4], 6, [1, 2]), ([3,3], 6, [0,1])]

for nums, target, result in checks:
    assert twoSum(nums, target)
    print(result)
[0, 1]

[1, 2]

[0, 1]