Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions data_structures/arrays/majority_element.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
def majority_element(arr: list[int]) -> int | None:
"""
Find the majority element in an array using the Boyer-Moore Voting Algorithm
The majority element is the element that appears more than n/2 times (n is the size of the array)

Check failure on line 4 in data_structures/arrays/majority_element.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

data_structures/arrays/majority_element.py:4:89: E501 Line too long (101 > 88)

Args:
arr(list[int]): The input array

Check failure on line 8 in data_structures/arrays/majority_element.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/arrays/majority_element.py:8:1: W293 Blank line contains whitespace
Returns:
int | None: The majority element if it exists

Check failure on line 11 in data_structures/arrays/majority_element.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/arrays/majority_element.py:11:1: W293 Blank line contains whitespace
Examples:
>>> majority_element([3, 3, 4, 2, 4, 4, 2, 4, 4])
4
>>> majority_element([2, 2, 1, 1, 1, 2, 2])
2
>>> majority_element([1, 2, 3])
None
>>> majority_element([])
None
"""

count = 0
majority = None

for num in arr:
if count == 0:
majority = num
count = 1
elif num == majority:
count += 1
else:
count -= 1

Check failure on line 34 in data_structures/arrays/majority_element.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/arrays/majority_element.py:34:1: W293 Blank line contains whitespace
if majority is not None and arr.count(majority) > len(arr) // 2:
return majority
return None


if __name__ == "__main__":
arr = [3, 3, 4, 2, 4, 4, 2, 4, 4]
print("Majority element: ", majority_element(arr))

Check failure on line 42 in data_structures/arrays/majority_element.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W292)

data_structures/arrays/majority_element.py:42:55: W292 No newline at end of file
Loading