r/DailyCodingProblem • u/T4ll1n • Mar 30 '22
Daily Coding Problem: Problem #4 [Hard] - 2022-03-30
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.
1
Upvotes
View all comments
1
u/T4ll1n Mar 30 '22
my first straight forward solution just goes through all ints and checks if they are in the list.
Trying to make it faster, only made it messy and not really helped.
but using set() to get the unique values definitely helps with speed.
googling actually shows that itertools already has a count function that just counts upwards
https://stackoverflow.com/a/41111471
timing it because why not
lets also add the set() call to my first simple try:
we can see that the first out of the box solution just advanced by the set() call already halves the required time from .046 to 0.28 and is almost identical to the one using the googled itertools count() method.