two_sums

Solution

	
	"""
https://leetcode.com/problems/two-sum/description/
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.
"""

from typing import List


def two_sums(arr: List[int], target: int) -> List[int]:
    values = {}  # value -> index in arr
    for i, value in enumerate(arr):
        value_needed = target - value
        if value_needed in values:
            return [values[value_needed], i]
        else:
            values[value] = i
    raise RuntimeError("not reachable")

	

Tests

	
	from publicmatt.leet.problems.two_sums import two_sums


def test_simple():
    nums = [2, 7, 11, 15]
    target = 9
    assert two_sums(nums, target) == [0, 1]


def test_another():
    nums = [3, 2, 4]
    target = 6
    assert two_sums(nums, target) == [1, 2]


def test_duplicate():
    nums = [3, 3]
    target = 6
    assert two_sums(nums, target) == [0, 1]

	
two_sums