Hashmap solution (Javascript)

  • 0

    Using the negative number trick seems confusing and less intuitive. I think using a hashmap works better, because it easily handles duplicates and lends itself better to these kinds of problems. The general idea is fairly simple: create a hashmap of all values in the array, then loop through it again but as numbers 1 -> array length, and compare i to the hash values. If it's not found in the map it's added to the return.

     * @param {number[]} nums
     * @return {number[]}
    var findDisappearedNumbers = function(nums) {
        const foundNums = new Map();
        const result = [];
        for (let i = 0; i < nums.length; i++) {
            foundNums.set(nums[i], i);
        for (let i = 1; i <= nums.length; i++) {
            if (!foundNums.has(i)) {
        return result;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.