Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- The intution behind code is put the positive numbers as it's index if [3,1,2] is there then make it like [1,2,3] so every elmenet is at the ele-1 position of the array that's what we have to use, swap until the whole array elements will reach it's place.
- ->We only care about the positive integers ranging 1 to n so answer can be in range of 1 to n+1(when 1 to n is in the array) so we will only keep swapping numbers if they are in range of 1 to n.swapping of nums[i] will happen to nums[i]-1 as our array follow 0 based indexing.
- ->To avoid duplicacy, we will check if the elemnt we are swapping and where we are swapping, they should not be same otherwise we will be in forever loop.
- ->finally travel the array, if nums[i]!=i+1, this is the first positive element.
- We should break at current i(for eg. 2) because may be 3 might be ahead
- '''
- class Solution:
- def firstMissingPositive(self, nums: List[int]) -> int:
- for i in range(len(nums)):
- cur_ele=nums[i]
- while nums[i]>=1 and nums[i]<=len(nums) and nums[i]!=nums[nums[i]-1]: #to save duplicate cases like (1,1) on 1st index
- pos=nums[i]-1
- nums[i],nums[pos]=nums[pos],nums[i]
- for i in range(len(nums)):
- if nums[i]!=i+1:
- return i+1
- return len(nums)+1
Advertisement
Add Comment
Please, Sign In to add comment