Element Appearing More Than 25% In Sorted Array - Problem

Given an integer array arr sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time.

Return that integer.

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,2,2,6,6,6,6,10]
Output: 6
💡 Note: Array length is 8, so 25% is 2 elements. Element 6 appears 4 times, which is more than 25% (4 > 2), so return 6.
Example 2 — Different Majority Element
$ Input: arr = [1,1,2,2,3,3,3,3,3]
Output: 3
💡 Note: Array length is 9, so 25% is 2.25, meaning we need more than 2 elements. Element 3 appears 5 times (5 > 2.25), so return 3.
Example 3 — Minimum Case
$ Input: arr = [1,1,1,2]
Output: 1
💡 Note: Array length is 4, so 25% is 1 element. Element 1 appears 3 times (3 > 1), so return 1.

Constraints

  • 1 ≤ arr.length ≤ 104
  • -106 ≤ arr[i] ≤ 106
  • arr is sorted in non-decreasing order

Visualization

Tap to expand
Element Appearing More Than 25% In Sorted Array INPUT Sorted Array (n=8) 1 idx:0 2 idx:1 2 idx:2 6 idx:3 6 idx:4 6 idx:5 6 idx:6 10 idx:7 Input Details arr = [1,2,2,6,6,6,6,10] Length n = 8 25% threshold = 8/4 = 2 = Appears more than 25% ALGORITHM STEPS 1 Calculate Threshold threshold = n/4 = 8/4 = 2 2 Linear Scan Compare arr[i] with arr[i+n/4] 3 Check Condition If arr[i] == arr[i+2], found! 4 Early Exit Return element immediately Scan Process i=0: arr[0]=1, arr[2]=2 X i=1: arr[1]=2, arr[3]=6 X i=2: arr[2]=2, arr[4]=6 X i=3: arr[3]=6, arr[5]=6 X i=4: arr[4]=6, arr[6]=6 OK --> Found! Return 6 FINAL RESULT Output 6 Why 6? Element 6 appears 4 times Frequency: 4/8 = 50% 50% > 25% threshold Condition satisfied! Time Complexity O(n) - Linear Scan Key Insight: Since the array is sorted, any element appearing more than 25% of the time must span at least n/4 consecutive positions. By comparing arr[i] with arr[i + n/4], we can detect if the element at position i is the answer. This allows early exit without counting all occurrences. TutorialsPoint - Element Appearing More Than 25% In Sorted Array | Linear Scan with Early Exit Approach
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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