1287. Element Appearing More Than 25% In Sorted Array
EasyView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
In a sorted array, the element appearing more than 25% of the time must be among the elements at indices n/4, n/2, 3n/4. Check those candidates.
Algorithm
- 1Candidates: arr[n/4], arr[n/2], arr[3n/4].
- 2For each candidate: count occurrences using binary search. If count > n/4, return it.
Common Pitfalls
- •Array is sorted so binary search works. The dominant element must appear at one of those three index positions.
1287.cs
C#
// Approach: In a sorted array the element appearing > 25% must equal its neighbor at index+n/4; check each candidate.
// Time: O(n) Space: O(1)
public class Solution
{
public int FindSpecialInteger(int[] arr)
{
int n = arr.Length;
int quarter = n / 4;
for (int i = 0; i < n - quarter; ++i)
{
if (arr[i] == arr[i + quarter])
return arr[i];
}
throw new ArgumentException();
}
}Advertisement
Was this solution helpful?