Element Appearing More Than 25% In Sorted Array - Problem

You're given an integer array that's already sorted in non-decreasing order. Your mission is to find the special element that appears more than 25% of the time in the array.

The problem guarantees that exactly one integer meets this criteria. For example, in an array of 4 elements, you need to find the element that appears at least 2 times (since 25% of 4 is 1, so "more than 25%" means at least 2 occurrences).

Key Points:

  • Array is sorted in non-decreasing order
  • There's always exactly one element that appears more than 25% of the time
  • Return that dominant element

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,2,2,6,6,6,6,7,10]
โ€บ Output: 6
๐Ÿ’ก Note: The array has 9 elements. 25% of 9 is 2.25, so we need an element appearing more than 2.25 times (at least 3 times). Element 6 appears 4 times, which is more than 25% of the array.
example_2.py โ€” All Same Elements
$ Input: [1,1]
โ€บ Output: 1
๐Ÿ’ก Note: The array has 2 elements. 25% of 2 is 0.5, so we need an element appearing more than 0.5 times (at least 1 time). Element 1 appears 2 times, which is 100% > 25%.
example_3.py โ€” Larger Array
$ Input: [1,2,3,3,3,3,3,4,5]
โ€บ Output: 3
๐Ÿ’ก Note: The array has 9 elements. We need an element appearing more than 2.25 times. Element 3 appears 5 times, which clearly exceeds 25% of the array size.

Constraints

  • 1 โ‰ค arr.length โ‰ค 104
  • -106 โ‰ค arr[i] โ‰ค 106
  • arr is sorted in non-decreasing order
  • Exactly one integer appears more than 25% of the time

Visualization

Tap to expand
1226666710n/4 positionn/2 position โœ“3n/4 positionElement 6 dominates with 4/9 = 44.4% > 25%Key InsightCheck positions n/4, n/2, 3n/4Dominant element must be there!
Understanding the Visualization
1
Understand the threshold
Calculate 25% of array length to determine minimum occurrences needed
2
Identify key positions
The dominant element must appear at positions n/4, n/2, or 3n/4 in sorted array
3
Check candidates
Count occurrences of elements at these strategic positions
4
Return the winner
The element exceeding the threshold is our answer
Key Takeaway
๐ŸŽฏ Key Insight: In a sorted array, any element appearing more than 25% of the time must occupy at least one of the strategic positions n/4, n/2, or 3n/4, making the solution extremely efficient!
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
42.3K 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