From 33798cf043632d57479ba39ded1693e17ab22260 Mon Sep 17 00:00:00 2001 From: t0xa Date: Mon, 19 Jan 2026 20:09:28 +0300 Subject: [PATCH] Algocode: add two_sums solution --- algocode/hash_tables/__init__.py | 0 algocode/hash_tables/two_sum.py | 120 +++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 algocode/hash_tables/__init__.py create mode 100644 algocode/hash_tables/two_sum.py diff --git a/algocode/hash_tables/__init__.py b/algocode/hash_tables/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/algocode/hash_tables/two_sum.py b/algocode/hash_tables/two_sum.py new file mode 100644 index 0000000..49b70a2 --- /dev/null +++ b/algocode/hash_tables/two_sum.py @@ -0,0 +1,120 @@ +""" +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. + +Example 1: + +Input: nums = [2,7,11,15], target = 9 +Output: [0,1] +Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. +Example 2: + +Input: nums = [3,2,4], target = 6 +Output: [1,2] +Example 3: + +Input: nums = [3,3], target = 6 +Output: [0,1] + +Constraints: + +2 <= nums.length <= 104 +-109 <= nums[i] <= 109 +-109 <= target <= 109 +Only one valid answer exists. +""" + + +""" +Допустим у нас будет хэшмапа, где будет лежать следующая пара ключ-значение: + + { + <сколько_не_хватает_до_цели> : + } + +Пробуем пройтись по очереди на первом примере +0. delta = {} +1. nums[0] = 2 + +delta = { + 7:0 +} + +2. nums[1] = 7 +2.1 Проверяем, есть ли в delta ключ `0`? +2.2 Да - получается наш ответ : [0,1] + +--- + +Example 2 +Input: nums = [3,2,4], target = 6 + +0. delta = {} +1. nums[0] = 3 +sub = target - 3 = 3 + +delta = { + 3:0 +} + +2. nums[1] = 2 +2.0 index = 1 +2.1 Есть ли в delta ключ 2? -> нет, следовательно: +2.2 sub = target - 2 = 4 + +delta = { + 3:0 + 4:1 +} + +3. nums[2] = 4 +3.0 index = 2 +3.1 Есть ли в delta ключ 4? -> Есть +3.2 Возвращаем [delta[4], index] + + +""" + +class Solution: + def twoSum(self, nums, target: int): + if len(nums) == 2: + return [0,1] + delta = dict() + for index, element in enumerate(nums): + if index == 0: + delta[target - element] = index + continue + res = delta.get(element) + if isinstance(res, int): + return [index, res] + sub = target - element + delta[sub] = index + raise ValueError("Cannot find valid answer") + +s = Solution() +nums = [2,7,11,15] +target = 9 +# Output: [0,1] +""" +1 +delta = { + 7:0 +} + +2 + +""" +assert s.twoSum(nums, target) in [[0,1], [1,0]], f"result = {s.twoSum(nums,target)}" + +nums = [3,2,4] +target = 6 +# Output: [1,2] +assert s.twoSum(nums, target) in [[1,2], [2,1]] + +nums = [3,3] +target = 6 +# Output: [0,1] +assert s.twoSum(nums, target) in [[0,1], [1,0]]