I am solving interview questions from here.
Problem : Given an integer array, find if an integer p exists in the array such that the number of integers greater than p in the array equals to p. If such an integer is found return 1 else return -1
Approach First remove all the negative numbers from the given array and then sort it. Now from the sorted array check for the given condition.
How can I optimize my solution :
def solve(A):
p = -1
sum_ind = 0
sub_array = [x for x in A if x>=0]
sub_array.sort()
print sub_array
for i in range(len(sub_array)):
for j in range(i+1,len(sub_array)):
if sub_array[j] > sub_array[i]:
sum_ind += 1
if sub_array[i] == sum_ind:
p = 1
break
else:
sum_ind = 0
return p
Test Cases:
print solve([ ]) == (-1)
print solve([ -1, -2, 0, 0, 0, -3 ]) == (1)
print solve([4,7,8,9,11]) == (1)
print solve([-4, -2, 0, -1, -6 ]) == (1)
print solve([-4, -2, -1, -6 ]) == (-1)
print solve([6,7,5 ]) == (-1)
print solve([ 4, -9, 8, 5, -1, 7, 5, 3 ]) == (1)