This approach uses the properties of the array and its indices to track missing numbers. By iterating through the array and using the values to mark the corresponding indices, we can identify which indices were never marked and thus determine the missing numbers.
Steps:
nums
.Time Complexity: O(n) - where n is the number of elements in the array because we are iterating over the array twice.
Space Complexity: O(1) - as no additional data structure is used apart from the output list and input array is modified in-place.
1class Solution:
2 def findDisappearedNumbers(self, nums):
3 for num in nums:
4 index = abs(num) - 1
5 nums[index] = -abs(nums[index])
6 missing = []
7 for i, num in enumerate(nums):
8 if num > 0:
9 missing.append(i + 1)
10 return missing
This Python solution modifies the input list nums
in-place by negating the elements at indices derived from the list values, facilitating detection of missing numbers in a final iteration.
In this approach, we utilize a set to only store unique numbers from 1 to n that appear in the input array. By comparing this set to the complete range of numbers, we can directly determine those not present in the input.
Steps:
nums
.Time Complexity: O(n)
Space Complexity: O(n), due to use of additional boolean array to track presence of numbers.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public IList<int> FindDisappearedNumbers(int[] nums) {
6 HashSet<int> numSet = new HashSet<int>(nums);
7 List<int> result = new List<int>();
8 for (int i = 1; i <= nums.Length; i++) {
9 if (!numSet.Contains(i)) {
10 result.Add(i);
11 }
12 }
13 return result;
14 }
15}
Using a HashSet
makes it efficient to manage unique number presence from nums
, forming the basis for identifying absent numbers through the list from 1 to n
.