|
| 1 | +# Given an array arr of n unique non-negative integers, how can you most efficiently find a non-negative integer that is not in the array? |
| 2 | + |
| 3 | +# Your solution should return such an integer or null if arr contains all possible integers. |
| 4 | +# Analyze the runtime and space complexity of your solution. |
| 5 | + |
| 6 | + |
| 7 | +import sys |
| 8 | + |
| 9 | + |
| 10 | +def find_int(arr): |
| 11 | + """ Takes an array and returns a non-negative integer that is not in the original array. Returns null if all integers are in the array. |
| 12 | +
|
| 13 | + Runtime: O(n) |
| 14 | + Spacetime: O(n) |
| 15 | +
|
| 16 | + >>> find_int([0, 2, 1, 3, 4, 5, 11, 32, 42, 50, 100, 6]) |
| 17 | + 7 |
| 18 | +
|
| 19 | + >>> find_int([2, 4, 5, 1, 3]) |
| 20 | + 0 |
| 21 | +
|
| 22 | + >>> find_int([0, 2, 4, 5, 1, 3]) |
| 23 | + 6 |
| 24 | +
|
| 25 | + >>> find_int([0, 2, 4, 5, 1, 3, 6, 8]) |
| 26 | + 7 |
| 27 | +
|
| 28 | + >>> find_int([]) |
| 29 | + 0 |
| 30 | +
|
| 31 | + """ |
| 32 | + |
| 33 | + arr2 = {} |
| 34 | + |
| 35 | + # If the length of the array is equal to the maximum allowed integers, there are no missing integers in the array. |
| 36 | + if len(arr) == sys.maxint: |
| 37 | + return None |
| 38 | + |
| 39 | + # Create an O(1) lookup hashtable using the integers from the array as the key, and set the value to True |
| 40 | + for i in range(len(arr)): |
| 41 | + arr2[arr[i]] = True |
| 42 | + |
| 43 | + # Loop through the length of the array + 1 and check if the number is a key in the hashtable. If it isn't return that number. |
| 44 | + for i in range(len(arr) + 1): |
| 45 | + if not arr2.get(i): |
| 46 | + return i |
| 47 | + |
| 48 | + return None |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == '__main__': |
| 52 | + import doctest |
| 53 | + results = doctest.testmod() |
| 54 | + |
| 55 | + if results.failed == 0: |
| 56 | + print 'ALL TESTS PASSED!' |
| 57 | + |
0 commit comments