From 71618c8fda92883c0864dd7455aeba83bb026406 Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 26 Dec 2024 05:01:25 -0600 Subject: [PATCH] adding two sum algo --- .../top_150_questions_round_12/two_sum.py | 16 ++++++++++++++++ .../test_two_sum_round_12.py | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_12/two_sum.py create mode 100644 tests/test_150_questions_round_12/test_two_sum_round_12.py diff --git a/src/my_project/interviews/top_150_questions_round_12/two_sum.py b/src/my_project/interviews/top_150_questions_round_12/two_sum.py new file mode 100644 index 00000000..9b1286c0 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_12/two_sum.py @@ -0,0 +1,16 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + + dic_answer = dict() + + for k, v in enumerate(nums): + + if v in dic_answer: + return [dic_answer[v], k] + + dic_answer[target - v] = k + + return -1 \ No newline at end of file diff --git a/tests/test_150_questions_round_12/test_two_sum_round_12.py b/tests/test_150_questions_round_12/test_two_sum_round_12.py new file mode 100644 index 00000000..3be239c3 --- /dev/null +++ b/tests/test_150_questions_round_12/test_two_sum_round_12.py @@ -0,0 +1,18 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_12\ +.two_sum import Solution + +class TwoSumTestCase(unittest.TestCase): + + def test_is_two_sum(self): + solution = Solution() + output = solution.twoSum(nums=[2,7,11,15], target=9) + target = [0,1] + for k, v in enumerate(target): + self.assertEqual(v, output[k]) + + def test_is_no_two_sum(self): + solution = Solution() + output = solution.twoSum(nums=[2,7,11,15], target=0) + target = -1 + self.assertEqual(output, target)