Check If a Number Is Majority Element in a Sorted Array Problem
Description
LeetCode Problem 1150.
Given an integer array nums sorted in non-decreasing order and an integer target, return true if target is a majority element, or false otherwise.
A majority element in an array nums is an element that appears more than nums.length / 2 times in the array.
Example 1:
Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
Output: true
Explanation: The value 5 appears 5 times and the length of the array is 9.
Thus, 5 is a majority element because 5 > 9/2 is true.
Example 2:
Input: nums = [10,100,101,101], target = 101
Output: false
Explanation: The value 101 appears 2 times and the length of the array is 4.
Thus, 101 is not a majority element because 2 > 4/2 is false.
Constraints:
1 <= nums.length <= 10001 <= nums[i], target <= 10^9numsis sorted in non-decreasing order.
Solution
Approach: One Binary Search
In a sorted array, all copies of target sit next to each other in one run. Binary search for first, the first index with nums[first] >= target. If target occurs at all, its run starts there.
target is a majority element when the run has more than n / 2 elements, that is, at least n / 2 + 1 (rounding n / 2 down). A run of that length starting at first covers index first + n / 2. And since the array is sorted, if that index still holds target, so does every index between them. So a single check is enough:
first + n / 2 < n and nums[first + n / 2] == target.
This also handles a target that does not occur: then nums[first] (if it exists) is already larger than target, and so is everything after it.
A second binary search for the end of the run, or a linear count, would work too, but they are not needed.
Complexity: O(log n) time and O(1) extra space.
import bisect
class Solution:
def isMajorityElement(self, nums: List[int], target: int) -> bool:
n = len(nums)
first = bisect.bisect_left(nums, target) # first index with nums[i] >= target
# target is a majority iff its run starting at `first` is longer than n / 2,
# i.e. it still covers index first + n // 2.
last = first + n // 2
return last < n and nums[last] == target