Missing Number In An Array
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n,
find the one that is missing from the array.
Example 1:
Input: myArray = [3, 0, 1]
Output: 2
Example 2:
Input: myArray = [0];
Output: 1
Solution using Javascript:
const missingNumber = (nums) => {
let number;
for (let i = 0; i <= nums.length; i += 1) {
if (nums.indexOf(i) === -1) {
number = i;
}
}
return number;
};
Test Cases
describe('missingNumber', () => {
test('should return 2', () => {
const myArray = [3, 0, 1];
expect(missingNumber(myArray)).toEqual(2);
});
test('should return 1', () => {
const myArray = [0];
expect(missingNumber(myArray)).toEqual(1);
});
test('should return 0', () => {
const myArray = [1];
expect(missingNumber(myArray)).toEqual(0);
});
});