#448

Find All Numbers Disappeared in an Array

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the properties of the input array itself to mark the presence of numbers. By using the indices of the array, we can identify which numbers are missing without using extra space.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate through the array and for each number, mark its corresponding index as negative to indicate that the number exists.
  2. 2Step 2: Iterate through the array again. The indices that remain positive correspond to the missing numbers.
  3. 3Step 3: Collect these indices (adjusted for 1-based indexing) into the result list.
solution.py7 lines
1# Full working Python code
2
3def findDisappearedNumbers(nums):
4    for num in nums:
5        index = abs(num) - 1
6        nums[index] = -abs(nums[index])
7    return [i + 1 for i in range(len(nums)) if nums[i] > 0]

Complexity note: The time complexity is O(n) because we traverse the array a constant number of times. The space complexity is O(1) since we modify the input array in place without using additional data structures.

  • 1The input array can be modified to track the presence of numbers without using extra space.
  • 2The range of numbers is guaranteed to be from 1 to n, which allows us to use the indices directly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.