DEV Community

nikhilkalariya
nikhilkalariya

Posted on

Missing Number

with using sort method to solve

function findMissingNumber(arr) {
    arr.sort((a, b) => a - b);
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] !== i + 1) {
            return i + 1;
        }
    }
    return arr.length + 1;
}

const numbers = [1, 2, 3, 4, 5, 6, 8, 9, 10];
const missingNumber = findMissingNumber(numbers);
console.log("The missing number is:", missingNumber);
Enter fullscreen mode Exit fullscreen mode

Without using any built in method

//third way to find missng number

function getMissingNo(arr1, n) {
    // The range is [1, N]
    const N = n + 1;
    // Calculate the sum of the range
    const totalSum = (N * (N + 1)) / 2;

    // Sum of elements in the array
    let arraySum = 0;
    for (let i = 0; i < n; i++) {
        arraySum += arr1[i];
    }

    // The missing number
    return totalSum - arraySum;
}

// Driver code
const arr1 = [1, 2, 3, 5];
const N = arr.length;
console.log(getMissingNo(arr1, N));

Enter fullscreen mode Exit fullscreen mode

With using reduce method to solve

//second way find missing job
function findMissingNumber(arr) {
  // Calculate the length of the array + 1 (since one number is missing)
  const n = arr.length + 1;

  // Calculate the expected sum of numbers from 1 to n
  const expectedSum = (n * (n + 1)) / 2;

  // Calculate the sum of numbers in the given array
  const actualSum = arr.reduce((acc, num) => acc + num, 0);

  // The difference between expectedSum and actualSum is the missing number
  const missingNumber = expectedSum - actualSum;

  console.log("The missing number is:", missingNumber);
  return missingNumber;
}

// Example usage
const arr = [1, 2, 4, 5, 6];
findMissingNumber(arr);  // Output will be: The missing number is: 3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)