Algorithm/NeetCode

First Missing Positive

Tony Lim 2024. 11. 12. 10:28
728x90

https://leetcode.com/problems/first-missing-positive/description/

class Solution:
    def firstMissingPositive(self, A: List[int]) -> int:
        for i in range(len(A)):
            if A[i] < 0:
                A[i] = 0

        for i in range(len(A)):
            val = abs(A[i])
            if 1 <= val <= len(A):
                if A[val -1] > 0:
                    A[val -1] *= -1
                elif A[val -1] == 0:
                    A[val-1] = -1 * (len(A) + 1)

        for i in range(1, len(A) + 1):
            if A[i - 1] >= 0:
                return i
        return len(A) + 1

1st iteration we neutralize negative value to zero

2nd iteration we mark value as negative to indicate certain number is in the A List

e.g) if checking 2 exist.  2 -1 = 1 (index) check A[1] value , if it's absolute value is  between 1 to len(A) we mark them with negative.

incase of 0 , we mark them as -1 * (len(A) +1) which is our worst case answer
e.g) [3,4,0,-1]  in case we check 3 exist , 3-1 =2 (index) abs value A[2] == 0 , we mark them as - 5 because in worst case A is going to be [1,2,3,4] and answer should be 5

at last iteration we check between 1 to len(A) and return if it is not in A otherwise return worst case

 

 

 

 

728x90

'Algorithm > NeetCode' 카테고리의 다른 글

Optimal Partition of String  (0) 2024.11.14
Number of Zero-Filled Subarrays  (0) 2024.11.13
Non-decreasing Array  (2) 2024.11.11
Range Sum Query 2D - Immutable  (0) 2024.11.10
Check If a String Contains All Binary Codes of Size K  (0) 2024.11.09