SDE & MLE Prep

448. Find All Numbers Disappeared in an Array

Problem

nums has n values, each in the range [1, n]; some appear twice and others not at all. Return every number in [1, n] that is missing.

Example: [4,3,2,7,8,2,3,1] → [5,6]

Constraints: follow-up: O(n) time and no extra space besides the output.

Values are in [1, n]: for each value v, mark index v−1 by making it negative. Indices that stay positive are the missing numbers.

Complexity: O(n) time, O(1) extra space.

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        for v in nums:
            i = abs(v) - 1
            nums[i] = -abs(nums[i])
        return [i + 1 for i, v in enumerate(nums) if v > 0]