class Solution:
def specialArray(self, A: List[int]) -> int:
""" tc O(lgN) sc O(1)
a is non-negtive => x range is [1,n], check edge case when x = 0, should return -1
"""
#A.sort() not necessary since x is correlated with size of A instead of value
n = len(A)
l,r = 1,n # was 0,n+1 with l < r while loop
while l <= r: # here reduce extra work of checking l = r, if cnt qualify
mid = l + (r-l)//2 # check cases when r - l == 1 , mid = l
cnt = 0
for a in A:
if a >= mid:
cnt += 1
if cnt < mid: # mid is too big
r = mid -1
elif cnt == mid:
return mid
else: #cnt > mid :
l = mid + 1
return -1