Trying to solve Missing Number Problem below
Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
Its solution giving incorrect syntax error ,any help in this code,basically constructed array of size n+1, to leave a spot for the missing element. Then Assigned each val to -1 so we can see which position was not filled
let missingNumber = function(nums){
const sol =new Array(nums.length+1).fill(-1);
for (const num of nums)
{
sol[num] = num;
}
return sol.indexOf(-1);
}
console.log(missingNumber(5))
Error i get is
PS C:\VSB-PRO> node Fibo.js
C:\VSB-PRO\Fibo.js:5
const res = new Array(nums.length+1).fill(-1);
^
RangeError: Invalid array length
at missingNumber (C:\VSB-PRO\Fibo.js:5:17)
at Object.<anonymous> (C:\VSB-PRO\Fibo.js:18:13)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
Your help is appreciated
Regards,
Carolyn
it seems that you were thinking that you were going to pass in an array into your missingNumber function as you try to access the length property on the parameter. However, you pass in a regular number 5 into the function. This code should fix your issue as I pass in an array instead:
let missingNumber = function(nums) {
const sol = new Array(nums.length + 1).fill(-1);
for (const num of nums) {
sol[num] = num;
}
return sol.indexOf(-1);
}
console.log(missingNumber([5, 3, 2, 4]))
If that's not what your looking for, then I advise you look over your code to understand where the data is traveling when you pass it into your function in your code.