> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Majority Element Python Solution with Tests

> Tested Python solution for LeetCode 169 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 169, Easy. Topics: Array, Hash Table, Divide and Conquer, Sorting, Counting. [View on LeetCode](https://leetcode.com/problems/majority-element/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 169   # by problem number
lcpy gen -s majority_element   # by problem name
```

## Problem

Given an array `nums` of size `n`, return the majority element.

The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array.

### Examples

```
Input: nums = [3,2,3]
Output: 3
```

```
Input: nums = [2,2,1,1,1,2,2]
Output: 2
```

### Constraints

* n == nums.length
* 1 \<= n \<= 5 \* 10^4
* -10^9 \<= nums\[i] \<= 10^9

**Follow-up:** Could you solve the problem in linear time and in O(1) space?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/majority_element/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/majority_element/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    # Boyer-Moore Voting Algorithm
    def majority_element(self, nums: list[int]) -> int:
        candidate = 0
        count = 0

        for num in nums:
            if count == 0:
                candidate = num
            count += 1 if num == candidate else -1

        return candidate
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(1)  |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
