What does return -1 here mean?

Viewed 239

When looping up answers to some job interview questions, I got this bit of code and am confused as to what return -1 is doing, and I guess how this code is actually accomplishing the task.

#First Non-Repeating Integer in an Array
def firstNonRepeating(arr, n): 
  
    for i in range(n): 
        j = 0
        while(j < n): 
            if (i != j and arr[i] == arr[j]): 
                break
            j += 1
        if (j == n): 
            return arr[i] 
      
    return -1
      
# Driver code 
arr = [ 9, 4, 9, 6, 7, 4 ] 
n = len(arr) 
print(firstNonRepeating(arr, n)) 
3 Answers

It looks like it's being used as a sentinel value for when all the integers repeat, for example:

>>> a = [9, 4, 9, 4]
>>> firstNonRepeating(a, len(a))
-1

However, that's a terrible choice of sentinel value, because it's also a perfectly legal value:

>>> arr = [-1]
>>> print(firstNonRepeating(arr, len(arr)))
-1

It would be better to raise an exception, like:

raise ValueError('no non-repeating integer found')

Maybe the writer was thinking of unsigned integers, which don't exist in Python (at least not as a native type). There are a bunch of other oddities that make me think it was written by someone more familiar with say, C, than Python (namely, passing in the length of an array, looping over numbers with while instead of for ... range, referring to a list/sequence as an array, and parentheses around the if tests).

The return -1 is for when every element in the array is repeating

Ex:

Input - 1, 1, 1
Output - -1

Generally when there is no solution present for the given input, then for indication purpose -1 is returned as the answer.

Here function firstNonRepeating will return -1 when all the integers present at least twice in the array.

Related