Why does this code does not pass all test cases? (Finding the smallest positive integer in a given array)

Question:

For the following coding Challenge:

Write a function:

def solution(A)

that, 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.

I wrote this code:

def solution(A):
    A.sort()
    B = list(set(A))
    for x in range(B[0],B[-1]):
        if x not in A and x>0:
            return x
    if B[-1]<0:
        return 1
    else:
        return B[-1]+1

But unfortunately it only passes in 5 of 8 test cases. What I might be forgetting to do?

Asked By: plshelpmeout

||

Answers:

If I understand the problem correctly, this is try to find the smallest positive number not in the given list, and the list can have negative/positive nums… There are some logic errors in the original code.

Prob. you can try this snippet, to see if that help you and compare?

def firstMissing(nums: List[int]) -> int:
    
    nums.append(0)
    N = len(nums)
        
    for i in range(N): # delete those useless elements
        if nums[i] < 0 or nums[i] >= N:  nums[i]=0
    for i in range(N): 
        #use the index as the hash to record the frequency of each number
        nums[nums[i]% N] += N
            
    for i in range(1, N):
        if nums[i] // N == 0: 
            return i
    return n

Outputs of testing:

firstMissing([1, 2, 3])     #    4
firstMissing([-1, -3])      #    1
firstMissing([1, 3, 6, 4, 1, 2])  # 5 
Answered By: Daniel Hao
def solution(array):
    smallest = 1
    new_arr = list(set([i for i in array if i>0]))
    new_arr.sort()
    for i in new_arr:
        if i<=smallest:
            smallest+=1
        else:
            break
    return smallest

x = solution([1, 3, 6, 4, 1, 2])
print(x) # 5

a little improved solution, by taking @DanielHao solution approach as a reference

def solution(array):
    smallest = 1
    new_arr = [0 for i in range(len(array))]
    for i in array:
        if 1<= i<= len(array):
            new_arr[i-1] = 1
    
    mini = 1
    for i, v in enumerate(new_arr, 1):
        if v==0:
            return i
    return len(new_arr)+1

why is your code is failing?

   for x in range(B[0],B[-1]):
        if x not in A and x>0:
            return x

just look this piece of code. you are return first value in range(b[0], b[-1]) which is not in A.

so lets say b[0] = 12, and b[-1] = 100
and your a =[12, 100]

so according you your this piece of code, first value here is 13 which is not in the A. so you considering it as solution and returning it.

which is wrong as 1 is also not there. so minimum should be 1.

so what you could do add condition where you check if mini = 1 is less than b[0] if yes then retiurn it and otherwise loop over and get the value which is greater than b[0] and not present in this range
ie

before this code

mini = 1
if mini < b[0]:
   return 0

so correct version of your code is

def solution2(A):
    A.sort()
    B = list(set(A))
    mini = 1
    if mini<B[0]:
        return mini
    for x in range(B[0],B[-1]):
        if x not in A and x>0:
            return x
    if B[-1]<0:
        return 1
    else:
        return B[-1]+1
Answered By: sahasrara62

The problem with your solution is that the lower bound of the range is the minimum of A and it should be 1 (if A = [2,3] the answer should be 1). Also a set has no order by default and hence you should sort it after. Here’s a neat solution.

1st line: You sort the list of the set of the elements.

2nd line: You create a list of integers that are not in A that range from 1 to the maximum between 2 (for the cases of full negative lists) and b[-1]+2 (the next integer after the greatest number in A) (2 and +2 given the fact that the range is exclusive). Finally we chose the first number of this list.

def solution(A):
    b=sorted(list(set(A)))
    return [i for i in range(1, max(b[-1]+2,2)) if i not in b][0]

Happy Coding!

Answered By: Daniel Gonçalves
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.