Lv.1arraycountinghash
Majority Element
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given an integer array nums in which exactly one value appears more than half of the time, return that majority value.
Examples
| nums | result |
|---|---|
[3, 2, 3] | 3 |
[2, 2, 1, 1, 1, 2, 2] | 2 |
[-7] | -7 |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(nums: int[]) → int
Constraints
-
nums.length -
nums[i] - A majority element (more than occurrences) always exists.
Expected complexity
- Time
- O(N)
- Space
- O(1)
Examples
| nums | Expected |
|---|---|
[3,2,3] | 3 |
[2,2,1,1,1,2,2] | 2 |
[-7] | -7 |
Hint
Hint
Counting with a hash map is . For extra space use the Boyer–Moore vote: keep a candidate and a counter, adopt the current value when the counter is 0, add one on a match and subtract one otherwise. Recounting the whole array for every element is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1058 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 4 | verdict only |