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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public IList<int> FindDisappearedNumbers(int[] nums) {
6 for (int i = 0; i < nums.Length; i++) {
7 int index = Math.Abs(nums[i]) - 1;
8 nums[index] = Math.Abs(nums[index]) * -1;
9 }
10 List<int> result = new List<int>();
11 for (int i = 0; i < nums.Length; i++) {
12 if (nums[i] > 0) {
13 result.Add(i + 1);
14 }
15 }
16 return result;
17 }
18}
This C# code achieves a similar goal by negating the numbers at positions that correspond to the array values encountered. Missing numbers are identified where the indices remain positive after processing.
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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <stdbool.h>
4
5int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {
6 bool* seen = calloc(numsSize + 1, sizeof(bool));
7 for (int i = 0; i < numsSize; i++) {
8 seen[nums[i]] = true;
9 }
10 int* result = malloc(numsSize * sizeof(int));
11 *returnSize = 0;
12 for (int i = 1; i <= numsSize; i++) {
13 if (!seen[i]) {
14 result[(*returnSize)++] = i;
15 }
16 }
17 free(seen);
18 return result;
19}
In this solution, a boolean array acts as a set storing flags for numbers detected in the input. Subsequent traversal is made to seek indices flagged false, representing the missing numbers.