From 7f71bd5267d77ae60a298ba595449ce2139d2079 Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 23 Sep 2025 04:25:03 -0600 Subject: [PATCH] adding algo --- .../majority_element.py | 20 +++++++++++++++++++ .../test_majority_element_round_20.py | 17 ++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_20/majority_element.py create mode 100644 tests/test_150_questions_round_20/test_majority_element_round_20.py diff --git a/src/my_project/interviews/top_150_questions_round_20/majority_element.py b/src/my_project/interviews/top_150_questions_round_20/majority_element.py new file mode 100644 index 00000000..ce87ab07 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_20/majority_element.py @@ -0,0 +1,20 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def majorityElement(self, nums: List[int]) -> int: + + dic_answer = dict() + len_nums = len(nums) + + for i in range(len_nums): + + if nums[i] not in dic_answer: + dic_answer[nums[i]] = 1 + else: + dic_answer[nums[i]] +=1 + + if dic_answer[nums[i]] > len_nums//2: + return nums[i] + + return -1 \ No newline at end of file diff --git a/tests/test_150_questions_round_20/test_majority_element_round_20.py b/tests/test_150_questions_round_20/test_majority_element_round_20.py new file mode 100644 index 00000000..95d04391 --- /dev/null +++ b/tests/test_150_questions_round_20/test_majority_element_round_20.py @@ -0,0 +1,17 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_20\ +.majority_element import Solution + +class MajorityElementTestCase(unittest.TestCase): + + def test_is_major_element(self): + solution = Solution() + output = solution.majorityElement(nums=[3,2,3]) + target = 3 + self.assertEqual(output, target) + + def test_is_no_major_element(self): + solution = Solution() + output = solution.majorityElement(nums = [1,2,3]) + target = -1 + self.assertEqual(output, target) \ No newline at end of file