Given an integer array arr
sorted in non-decreasing order, there is exactly one integer in the array that appears more than 25% of the time. Return that integer.
arr = [1,2,2,6,6,6,6,7,10]
6
arr.length
<= 10^4arr[i]
<= 10^5Given that the array is sorted:
len(arr) // 4
.An effective approach in a sorted array is to leverage the fact that elements will cluster together. Thus:
threshold + 1
, return that element immediately.This approach ensures a single pass through the array, making it efficient.
def findSpecialInteger(arr):
threshold = len(arr) // 4
current_element = arr[0]
count = 1
for i in range(1, len(arr)):
if arr[i] == current_element:
count += 1
else:
current_element = arr[i]
count = 1
if count > threshold:
return current_element
return current_element # Should never be reached given problem constraints
# Example Test
arr = [1, 2, 2, 6, 6, 6, 6, 7, 10]
print(findSpecialInteger(arr)) # Output: 6
The time complexity of the solution is O(n) where n
is the length of the array arr
. This is because it involves a single pass through the array to count the frequency of each element.
threshold
, current_element
, and count
are used to maintain state as we iterate through the array.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?