Element Appearing More Than 25% In Sorted Array Problem
Description
LeetCode Problem 1287.
Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
Example 1:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Example 2:
Input: arr = [1,1]
Output: 1
Constraints:
1 <= arr.length <= 10^40 <= arr[i] <= 10^5
Solution
Approach: Compare With the Element a Quarter Ahead
In a sorted array equal values sit next to each other. Let n be the length and step = n / 4 (rounded down). The special value appears more than n / 4 times, so at least step + 1 times, and its run covers some index i and also i + step. That is, arr[i] == arr[i + step].
No other value can pass this test. It appears at most n / 4 times, and since a count is a whole number, at most step times; its run covers at most step positions, so it never reaches from i to i + step. So we scan i from the left and return the first arr[i] that equals arr[i + step].
For short arrays (n < 4) step is 0 and the first element is returned, which is right: with fewer than 4 elements every value present appears more than 25% of the time, so the guarantee of exactly one such value means all elements are equal.
Complexity: O(n) time and O(1) extra space.
class Solution:
def findSpecialInteger(self, arr: List[int]) -> int:
step = len(arr) // 4
for i, x in enumerate(arr):
# A run of more than n/4 equal values spans arr[i] .. arr[i + step].
if arr[i + step] == x:
return x
return -1 # the problem guarantees an answer, so this is never reached