Check If a Number Is Majority Element in a Sorted Array - Problem

Given an integer array nums sorted in non-decreasing order and an integer target, determine if the target is a majority element in the array.

A majority element is an element that appears more than nums.length / 2 times in the array. In other words, it must appear in more than half of the array positions.

Key insight: Since the array is already sorted, all occurrences of the target (if any) will be grouped together consecutively. This property allows us to use efficient searching algorithms instead of counting each element.

Goal: Return true if target appears more than n/2 times, false otherwise.

Input & Output

example_1.py โ€” Basic Majority Case
$ Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
โ€บ Output: true
๐Ÿ’ก Note: The target 5 appears 5 times in the array of length 9. Since 5 > 9/2 (4.5), it's a majority element.
example_2.py โ€” Not Majority
$ Input: nums = [10,100,101,101], target = 101
โ€บ Output: false
๐Ÿ’ก Note: The target 101 appears 2 times in the array of length 4. Since 2 = 4/2, it's not more than half, so not a majority element.
example_3.py โ€” Target Not Found
$ Input: nums = [1,1,2,3,3,4,4], target = 5
โ€บ Output: false
๐Ÿ’ก Note: The target 5 doesn't exist in the array, so it can't be a majority element.

Visualization

Tap to expand
Binary Search Majority Element DetectionSorted Array122444446Target: 4Range of target occurrencesBinary Search ResultsFirst occurrence at index: 3Last occurrence at index: 7Count = 7 - 3 + 1 = 55 > 9/2 โœ“ โ†’ Majority Element!Time: O(log n) | Space: O(1)
Understanding the Visualization
1
Binary Search Left
Find the leftmost occurrence of the target using binary search
2
Binary Search Right
Find the rightmost occurrence of the target using binary search
3
Calculate Range
Count = right_index - left_index + 1
4
Check Majority
Return count > array_length / 2
Key Takeaway
๐ŸŽฏ Key Insight: Since the array is sorted, identical elements form consecutive groups. Binary search can efficiently find group boundaries in O(log n) time, making this much faster than O(n) linear counting!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Must examine every element once to count occurrences

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only uses a single counter variable

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • -109 โ‰ค nums[i], target โ‰ค 109
  • nums is sorted in non-decreasing order
Asked in
Google 42 Amazon 35 Meta 28 Microsoft 31
38.2K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen