Advertisement

Responsive Advertisement

Find All Numbers Disappeared in an Array LeetCode Solution

Find All Numbers Disappeared in an Array LeetCode Solution
Find All Numbers Disappeared in an Array LeetCode Solution


Approach


This code defines a function called "findDisappearedNumbers" that takes in an array of numbers and returns an array of numbers that are missing from the input array. The function first creates a new Set from the input array, which automatically removes any duplicate values. Next, it creates an empty array called "res" which will be used to store the missing numbers. The function then uses a for loop to iterate through the range of 1 to the length of the input array + 1. For each iteration, it checks if the current number (i) is not in the set (using the "has" method). If it is not, it pushes that number to the "res" array. Finally, the function returns the "res" array which contains the missing numbers.

Complexity

  • Time complexity:


The time complexity of this function is O(n), which means that the running time of the function increases linearly with the size of the input array. The function uses a single for loop that iterates through all elements of the input array once, and for each element, it performs a constant-time operation (checking if the element is in the set) and a constant-time operation (pushing an element to an array). Therefore, the overall time complexity is O(n).

  • Space complexity:


The space complexity of this function is O(n) as well, which means that the amount of memory used by the function increases linearly with the size of the input array. The function creates a new Set from the input array, which takes O(n) space. It also creates a new array "res" to store the missing numbers, which also takes O(n) space. Therefore, the overall space complexity is O(n).
O(N)

Code:

function findDisappearedNumbers(nums: number[]): number[] {
    let set = new Set(nums);
    let res: number[] = [];

    for (let i = 1; i < nums.length + 1; i++){
        if(!set.has(i)){
            res.push(i);
        }
    }
    return res;
};