the problem statement is:
given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Can anyone tell me what the time-complexity of the following solution to the code be:
def solution(A):
m = max(A)
if m < 1:
return 1
A = set(A)
B = set(range(1, m + 1))
D = B - A
if len(D) == 0:
return m + 1
else:
return min(D)
It has to be O(n) or greater because we are finding the max. I had a doubt if creating a set from range 1 to the max element will be nlogn as the result will be a sorted set of elements..?
m+1?set(range(1, m + 1)), though I thinkset(A)andB - Aare also very interesting for this question.set(B)is not sorted, becausesetsare not sorted in python. Considersolution([1,2,3])andsolution([1,2,1_000_000]): 1.21µs vs 107ms. Your algorithm's runtime depends mostly on the largest number in your array, because ofset(range(1, m+1)).