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, 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.

Input & Output

Example 1 — Target is Majority
$ Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
Output: true
💡 Note: Target 5 appears 5 times in array of length 9. Since 5 > 9/2 (which is 4), target 5 is a majority element.
Example 2 — Target is Not Majority
$ Input: nums = [10,100,101,101], target = 101
Output: false
💡 Note: Target 101 appears 2 times in array of length 4. Since 2 ≤ 4/2 (which is 2), target 101 is not a majority element.
Example 3 — Target Not Found
$ Input: nums = [1,1,2,2], target = 3
Output: false
💡 Note: Target 3 does not appear in the array, so it cannot be a majority element.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -109 ≤ nums[i], target ≤ 109
  • nums is sorted in non-decreasing order

Visualization

Tap to expand
Majority Element in Sorted Array INPUT Sorted Array nums[] 2 4 5 5 5 5 5 6 6 indices: 0 1 2 3 4 5 6 7 8 Input Parameters target = 5 nums.length = 9 Legend Target element (5) Other elements ALGORITHM STEPS 1 Binary Search First Find first occurrence of 5 firstIdx = 2 2 Binary Search Last Find last occurrence of 5 lastIdx = 6 3 Count Occurrences count = last - first + 1 count = 6 - 2 + 1 = 5 4 Check Majority count > n/2 ? 5 > 9/2 = 4.5 ? YES Binary Search Results firstIdx: 2 lastIdx: 6 count: 5 threshold: 4.5 FINAL RESULT true 5 is majority element Verification Element 5 appears 5 times Array length: 9 Threshold: 9/2 = 4.5 5 > 4.5 = TRUE Complexity Analysis Time: O(log n) Space: O(1) Key Insight: Since the array is sorted, all occurrences of target are contiguous. Using binary search to find the first and last positions gives us the count in O(log n) time, much better than O(n) linear scan. TutorialsPoint - Check If a Number Is Majority Element in a Sorted Array | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 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