GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — python-interview-questions/non_neg_int.py at master · anushabolishettii/python-interview-questions

Expand file tree

/

non_neg_int.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
57 lines (36 loc) · 1.44 KB
/

non_neg_int.py

Copy path

File metadata and controls

57 lines (36 loc) · 1.44 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 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?
# Your solution should return such an integer or null if arr contains all possible integers.
# Analyze the runtime and space complexity of your solution.
import sys
def find_int(arr):
""" 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.
Runtime: O(n)
Spacetime: O(n)
>>> find_int([0, 2, 1, 3, 4, 5, 11, 32, 42, 50, 100, 6])
7
>>> find_int([2, 4, 5, 1, 3])
0
>>> find_int([0, 2, 4, 5, 1, 3])
6
>>> find_int([0, 2, 4, 5, 1, 3, 6, 8])
7
>>> find_int([])
0
"""
arr2 = {}
# If the length of the array is equal to the maximum allowed integers, there are no missing integers in the array.
if len(arr) == sys.maxint:
return None
# Create an O(1) lookup hashtable using the integers from the array as the key, and set the value to True
for i in range(len(arr)):
arr2[arr[i]] = True
# 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.
for i in range(len(arr) + 1):
if not arr2.get(i):
return i
return None
if __name__ == '__main__':
import doctest
results = doctest.testmod()
if results.failed == 0:
print 'ALL TESTS PASSED!'
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.