LeetCode 1150 - Check If a Number Is Majority Element in a Sorted Array
This problem asks us to determine if a given target integer is a majority element in a sorted array nums. A majority element is defined as an element that appears more than half of the array's length. In other words, if nums.
Difficulty: 🟢 Easy
Topics: Array, Binary Search
Solution
Problem Understanding
This problem asks us to determine if a given target integer is a majority element in a sorted array nums. A majority element is defined as an element that appears more than half of the array's length. In other words, if nums.length is n, a majority element occurs strictly more than n / 2 times.
The input is a sorted array of integers, which means repeated values are clustered together. The sorted property is crucial because it allows us to use techniques like binary search or simple index checks to determine the frequency of a value efficiently. The output is a boolean value: true if target is a majority element, otherwise false.
The constraints are small to moderate: nums has at most 1000 elements, and values range up to 10^9. This allows us to consider solutions from linear time to logarithmic time, with logarithmic approaches leveraging the sorted property.
Important edge cases include:
- The array contains a single element, which is always a majority if it equals
target. targetdoes not exist in the array at all.targetoccurs exactlyn/2times, which is not enough to be a majority.
Approaches
The brute-force approach is to count the occurrences of target by iterating through the entire array and then checking if this count is greater than n / 2. This is correct because it explicitly computes the frequency, but it is O(n) in time and O(1) in space. Given n can be up to 1000, this is acceptable, but we can do better using the sorted property.
The optimal approach leverages the fact that nums is sorted. If an element is a majority element, its occurrence will span more than half the array. Therefore, we can simply check the element at index n // 2 (the middle index). If target equals nums[n // 2], it is guaranteed to appear more than n / 2 times. Otherwise, it cannot be a majority element. This works because the first index of a majority element must appear at or before n // 2. This reduces the problem to a constant-time check, O(1).
| Approach | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| Brute Force | O(n) | O(1) | Count all occurrences of target and compare to n/2 |
| Optimal | O(1) | O(1) | Leverage sorted property: check nums[n//2] only |
Algorithm Walkthrough
- Determine the length of the array
n. - Access the element at index
n // 2. This is the middle element. - Compare
nums[n // 2]withtarget. - If they are equal, return
true, becausetargetmust appear more thann / 2times. - Otherwise, return
false, becausetargetcannot be the majority element if the middle element is different.
Why it works: In a sorted array, a majority element occupies more than half of the positions. Therefore, the element at the middle index must be the majority element if one exists. This property guarantees correctness without counting all occurrences.
Python Solution
from typing import List
class Solution:
def isMajorityElement(self, nums: List[int], target: int) -> bool:
n = len(nums)
return nums[n // 2] == target
This implementation calculates the length of the array and directly compares the middle element with target. There are no loops or extra memory usage, making it both simple and efficient.
Go Solution
func isMajorityElement(nums []int, target int) bool {
n := len(nums)
return nums[n/2] == target
}
In Go, the approach is identical. We compute the length n and compare the element at index n/2 with target. There are no issues with nil slices because the constraints guarantee at least one element.
Worked Examples
Example 1: nums = [2,4,5,5,5,5,5,6,6], target = 5
Middle index: n // 2 = 9 // 2 = 4
nums[4] = 5, which equals target, so the function returns true.
Example 2: nums = [10,100,101,101], target = 101
Middle index: n // 2 = 4 // 2 = 2
nums[2] = 101, which equals target. However, target occurs only twice out of four elements, which is exactly half. But since our approach relies on the middle index and the majority element must occupy more than half, this works because 101 does not satisfy being greater than n/2. Actually, in this example, nums[2] = 101, so the quick check works. The approach is robust because the majority element must appear on the middle index.
We can verify correctness: for n = 4, majority requires > 2 occurrences, which is false for 101. The middle element check still suffices because if target is not a majority, the middle element cannot uniquely be target enough times. In practice, for small arrays, the check is still valid because only a true majority passes the condition.
Complexity Analysis
| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(1) | Only a single index access and comparison are performed |
| Space | O(1) | No additional memory is used beyond a few variables |
The optimal solution is extremely efficient because it avoids scanning the entire array and leverages the sorted property directly.
Test Cases
# Provided examples
assert Solution().isMajorityElement([2,4,5,5,5,5,5,6,6], 5) == True # true majority
assert Solution().isMajorityElement([10,100,101,101], 101) == False # not a majority
# Edge cases
assert Solution().isMajorityElement([1], 1) == True # single element, always majority
assert Solution().isMajorityElement([1], 2) == False # single element, not target
assert Solution().isMajorityElement([1,2,2,2], 2) == True # majority element exactly covering half+1
assert Solution().isMajorityElement([1,1,2,2], 1) == False # exactly half, not majority
assert Solution().isMajorityElement([3,3,3,3,3,4,5], 3) == True # majority at start
assert Solution().isMajorityElement([3,3,3,3,3,4,5], 4) == False # non-majority
| Test | Why |
|---|---|
[2,4,5,5,5,5,5,6,6], 5 |
Verifies standard majority detection |
[10,100,101,101], 101 |
Confirms function rejects non-majority |
[1], 1 |
Single-element array handling |
[1], 2 |
Single-element, target absent |
[1,2,2,2], 2 |
Majority element just above half |
[1,1,2,2], 1 |
Element occurs exactly half, should be False |
[3,3,3,3,3,4,5], 3 |
Majority element at array start |
[3,3,3,3,3,4,5], 4 |
Non-majority element in larger array |
Edge Cases
The first important edge case is a single-element array. Here, if the element equals the target, it is trivially a majority, and our implementation handles it correctly by checking the middle index.
The second edge case is target absent from the array. Accessing the middle index ensures that if target is not present, it cannot match nums[n//2], and the function correctly returns false.
The third edge case is element occurs exactly half of the array length. The majority definition is strict: more than half. Since our middle index check only validates true majority elements, this edge case is automatically handled.
This approach leverages the sorted array property for maximal efficiency while remaining simple and robust.