-
Notifications
You must be signed in to change notification settings - Fork 0
/
2020-01-28.py
77 lines (68 loc) · 2.57 KB
/
2020-01-28.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Given an array of integers, find the first missing positive integer in linear time and constant space.
In other words, find the lowest positive integer that does not exist in the array. The array can contain
duplicates and negative numbers as well.
For example, the input `[3, 4, -1, 1]` should give 2. The input `[1, 2, 0]` should give 3.
You can modify the input array in-place.
"""
import sys
from typing import List
Vector = List[int]
def find_missing_int(vec: Vector):
"""
map the sequence to 0...LEN-1
set neg values to 0
how to deal with neg values? bubble to the end?
find min, max, and length of array
if sorted, with all negs set to 0:
if pairwise difference in seq <= 1
return max(seq) + 1
else
return min(pair) + 1
TODO this surely can be simplified
:param vec: list of integers
:return: lowest integer not in the list
"""
if not vec:
return 1
input_len = len(vec)
min_val = sys.maxsize
max_val = - sys.maxsize - 1
for item in vec:
if 0 <= item > max_val:
max_val = item
if 0 <= item < min_val:
min_val = item
if sys.maxsize == min_val or min_val > 1:
return 1
if min_val == max_val:
if min_val == 1:
return 2
else:
return 1
# try to map the sequence to natural numbers: offset by min_val
for idx in range(input_len):
vec[idx] = vec[idx] - min_val if vec[idx] > 0 else 0
for idx in range(input_len):
# swap till idx find its corresponding value (which is min_val for idx 0)
while input_len > vec[idx] != idx and vec[idx] != vec[vec[idx]]:
_swap(vec, idx, vec[idx])
for idx in range(input_len - 1):
# find a gap
if vec[idx] < vec[idx + 1] - 1:
return vec[idx] + min_val + 1
# only if all values in the list could be mapped to a continuous sequence of natural numbers
return max_val + 1
def _swap(arr: Vector, curr_idx: int, new_idx: int):
val = arr[curr_idx]
arr[curr_idx] = arr[new_idx]
arr[new_idx] = val
if __name__ == "__main__":
assert find_missing_int([3, 4, -1, 1]) == 2
assert find_missing_int([1, 2, 0]) == 3
assert find_missing_int([1, 2, 0, 6, 5, 4, 8, 10, 9]) == 3
assert find_missing_int([3, 1, 2, 0, 6, 5, 4, 8, 10, 9]) == 7
assert find_missing_int([1, 1, 1, 1]) == 2
assert find_missing_int([10, 100, 10000, 100000]) == 1
assert find_missing_int([9, 8, 7, 6, 5, 4, 3, 2, 1]) == 10
assert find_missing_int([9, 8, 7, 6, 5, 4, 3, 2, 1, 11, 111, 1111]) == 10