Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

(LeetCode n.d.)

2sum is a Technical interview question and a variant of the Subset sum problem.

Quadratic solution (\(\bigo{n^2}\))

from typing import Optional, List

def two_sum(numbers: List[int], target: int) -> Optional[List[int]]:
    """Return the two elements in NUMBERS which sum to TARGET; else None."""

    for first in numbers:
        for second in numbers[1:]:
            if first + second == target:
                return [first, second]

    return None

print(two_sum([2,4,5], 7), 'should be [2, 5]')
print(two_sum([2,4,5], 2), 'should be None')

Linear solution (\(\bigo{n}\))

The trick is using a Hash map.

2sum linear time solution in Python

Bibliography

LeetCode. n.d. “Two Sum.” Leetcode. Accessed February 8, 2023. https://leetcode.com/problems/two-sum/description.