Leetcode 1287. Element Appearing More Than 25% In Sorted Array
You are given a sorted array of integers arr
, where each element appears at least once. Return any element that appears more than 25% of the time in the array.
1 <= arr.length <= 10^4
).Frequency Requirement: For an element to appear more than 25% of the time, it must be present at least n / 4
times in the array, where n
is the size of the array.
Binary Search Approach:
i
, i + n/4
, i + 2*n/4
, and i + 3*n/4
(ensuring no index out of bounds):
n / 4
.Here is the C++ implementation of the above strategy:
#include <vector>
#include <iostream>
#include <algorithm>
int findSpecialInteger(std::vector<int>& arr) {
int n = arr.size();
int threshold = n / 4;
for (int i = 0; i < n; i += threshold) {
int candidate = arr[i];
auto lower = std::lower_bound(arr.begin(), arr.end(), candidate);
auto upper = std::upper_bound(arr.begin(), arr.end(), candidate);
if (upper - lower > threshold) {
return candidate;
}
}
// This point should never be reached because there is always an element that appears more than 25%
return -1; // For safe return
}
int main() {
std::vector<int> arr = {1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6};
std::cout << "Element Appearing More Than 25%: " << findSpecialInteger(arr) << std::endl;
return 0;
}
std::lower_bound
and std::upper_bound
takes O(log n)
time.n / (n / 4) = 4
times.4 * (O(log n) + O(log n)) = O(log n)
.This approach is efficient and leverages the sorted nature of the array to achieve logarithmic time complexity in searching for the boundaries.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?