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 <= 104
0 <= arr[i] <= 105
This problem leverages the fact that the input array is sorted. The core idea is that if an element appears more than 25% of the time, it must appear within a quarter of the array's length.
Approach:
The solution iterates through the array. For each element, it checks if that element is also present at an index i + (n >> 2)
, where n
is the length of the array and (n >> 2)
is a bitwise right shift equivalent to integer division by 4 (finding a quarter of the array's length). If a match is found, it means the element appears at least twice within a quarter of the array, satisfying the condition of appearing more than 25% of the time.
Time Complexity Analysis:
The solution iterates through the array at most once. Therefore, the time complexity is O(n), where n is the length of the input array.
Space Complexity Analysis:
The solution uses only a few variables to store the array length and the current element's index. The space complexity is therefore O(1), which is constant space.
Code Explanation (Python):
class Solution:
def findSpecialInteger(self, arr: List[int]) -> int:
n = len(arr)
for i, val in enumerate(arr):
if val == arr[i + (n >> 2)]: #Check if the element is present a quarter of the array's length away
return val
return 0 #Should not reach here if the condition is met
The code directly implements the described approach. The enumerate
function provides both index and value during iteration. The condition val == arr[i + (n >> 2)]
efficiently checks for the presence of the same element within a quarter of the array's length.
Code Explanation (Other Languages):
The solutions in Java, C++, Go, JavaScript, and PHP follow the same logic as the Python solution, differing only in syntax. Each language's specific implementation efficiently utilizes its built-in features to achieve the same O(n) time and O(1) space complexity. The core logic of checking for element repetition within a quarter of the array remains consistent across all implementations.