You are given a non-negative integer array nums
. The special array is defined as an array where there exists a number x
such that there are exactly x
elements in the array that are greater than or equal to x
.
Return the smallest possible value of x
. If no such x
exists, return -1
.
nums
?
nums
are non-negative integers and could be very large.nums
?
nums
could vary from 1 to 1000.nums
will have at least one element as per constraint 1 <= nums.length.nums
. This helps in determining the number of elements greater than or equal to any number x
efficiently.x
:
x
from 0
to the length of the array. For each x
, we need to check if there are exactly x
elements greater than or equal to x
.x
, find the first position in the sorted array where the element is greater than or equal to x
using binary search.x
can then be determined by the length of the array minus this position.x
:
x
that meets the condition, return that x
.x
is found, return -1
.def specialArray(nums):
nums.sort()
n = len(nums)
for x in range(n + 1):
# Find the number of elements greater than or equal to `x`
idx = binary_search(nums, x)
if n - idx == x:
return x
return -1
def binary_search(nums, x):
left, right = 0, len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] >= x:
right = mid
else:
left = mid + 1
return left
# Example Usage:
nums = [3, 5, 0, 4, 3]
print(specialArray(nums)) # Output might be 3
x
:
0
to n
, resulting in ( O(n) ) operations.n+1
times, it gives ( O(n \log n) ).Overall, the dominant factor remains the sorting step, resulting in a final time complexity of ( O(n \log n) ).
This approach ensures that we efficiently identify the smallest possible x
or determine that no such x
exists.
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?