You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.
Return x if the array is special, otherwise return -1. Note that x does not have to be an element in nums.
nums contain duplicate values?
nums can contain duplicate values.nums?
nums?
x exists?
-1 if no such x exists.x from 0 to n (length of array):
x, count how many numbers in the array are greater than or equal to x.x, then return x.x is found during the iteration, return -1.Here’s the implementation in Python:
def specialArray(nums):
nums.sort()
n = len(nums)
for x in range(n + 1):
count = sum(1 for num in nums if num >= x)
if count == x:
return x
return -1
nums to ensure that we can easily count numbers greater than or equal to x.sum() function to count the number of elements in nums that are greater than or equal to the current x.x, we return x as it satisfies the condition.x, we return -1.O(n log n) where n is the length of the array.O(n), and as this happens n + 1 times, the overall cost is O(n^2).Therefore, the overall time complexity is O(n log n + n^2), which is dominated by O(n^2) due to the nested counting operation.
This approach should be efficient given the constraints (length up to 100).
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?