-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.py
More file actions
39 lines (28 loc) · 1.35 KB
/
Copy path4.py
File metadata and controls
39 lines (28 loc) · 1.35 KB
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
""" This problem was asked by Stripe.
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. """
input = [3, 4, -1, 1]
input_2 = [1, 2, 0]
def find_missing_int_naive(nums: list[int]) -> int:
nums.sort()
for i in range(len(nums) - 1):
if nums[i] >= 0:
expected = nums[i] + 1
next = nums[i + 1]
if next > expected:
return expected
return nums[-1] + 1
def find_missing_int(nums: list[int]):
for i in range(len(nums)):
while (1 <= nums[i] <= len(nums) and nums[nums[i] - 1] != nums[i]):
correct_index = nums[i] - 1
nums[i], nums[correct_index] = nums[correct_index], nums[i]
for i in range(len(nums)):
if (nums[i] != i + 1):
return i + 1
print(find_missing_int(input))
print(find_missing_int(input_2))
# poor man's hash table, use the perks of an array's sequential properties to find gaps in integer sequences
# two for loops -> 2n, while loop can never exceed n swaps, o(1) space, o(n) time
# DONE