Python O(n) time O(1) space Solution

  • 0

    Put the numbers in their place. If we see 1 we put it in nums[1], etc. Then go thru the array and see which one is missing.

    class Solution(object):
        def firstMissingPositive(self, nums):
            nums += 0,
            i,n = 0,len(nums)
            while i < n:
                if nums[i]==i or nums[i] < 0 or nums[i] >= n or nums[nums[i]]==nums[i]:
                    i += 1
                    nums[nums[i]],nums[i] = nums[i],nums[nums[i]]
            for i,num in enumerate(nums):
                if i != num: return i
            return n

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.