Skip to content

Commit

Permalink
"Majority Element" solution
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Feb 4, 2024
1 parent ef133d3 commit 147157c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/majority_element.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
def majorityElement(self, nums: list[int]) -> int:
result = nums[0]
count = 0

for num in nums:
if num == result:
count += 1
elif count == 1:
result = num
else:
count -= 1

return result
14 changes: 14 additions & 0 deletions tests/test_majority_element.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import pytest

from src.majority_element import Solution


@pytest.mark.parametrize(
"nums,expected",
(
([3, 2, 3], 3),
([2, 2, 1, 1, 1, 2, 2], 2),
),
)
def test_solution(nums, expected):
assert Solution().majorityElement(nums) == expected

0 comments on commit 147157c

Please sign in to comment.