a) takes O(n*lgn) time; the method in post uses O(n) time
b) use extra memory; the method in post uses O(1) extra memory
c) have logical error: the problem asks to find the first missing positive (in range [1, infinity)).
So firstMissingPositive([4,100]) should return 1, instead of 5. But the problem is not stated in the post, so let's assume you are implementing the first missing positive in range(A[0], A[-1] + 1) for sorted(A), your code does not handle corner case well.
For example:
a) your firstMissingPositive([100]) gives ValueError: min() arg is an empty sequence
b) your firstMissingPositive([]) gives IndexError: list index out of range
It is attempting to write three-liners that seems to solve the problem, but it is far more important to solve the problem in time and space efficient way. At least, it is important to handle the corner cases well.
def firstMissingPositive(A):
try:
for x in range(1, max(A)+1):
if x not in A: return x
except: return A
def firstMissingPositive(A):
try: return next(x for x in range(1, max(A)+1) if x not in A)
except: return A
Thanks for the ValueError tip. I added it as well as a TypeError just in case the input comes in as a string. My skills are beginner level at best, tips like yours help a lot!
Comments
The function you wrote:
So firstMissingPositive([4,100]) should return 1, instead of 5. But the problem is not stated in the post, so let's assume you are implementing the first missing positive in range(A[0], A[-1] + 1) for sorted(A), your code does not handle corner case well.For example:
It is attempting to write three-liners that seems to solve the problem, but it is far more important to solve the problem in time and space efficient way. At least, it is important to handle the corner cases well.Thanks for the reply, very informative.
You really should change "except" to "except ValueError" there.
Also, I suggest first converting A to a set. Just "A = set(A)" would work.
HN is not really for code review, but why are you using try and except here??
Python is designed for it, and it makes it cleaner, so why not?
EAFP: Easier to ask for forgiveness than permission
That being said, just a blanket except is a bad idea.
Thanks for the ValueError tip. I added it as well as a TypeError just in case the input comes in as a string. My skills are beginner level at best, tips like yours help a lot!