- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

We are required to write a JavaScript function that takes in an array of numbers of length, say n. The array contains all the integers from 0 to n (including both 0 and n), but just one integer is missing, it can be any number and the array is not sorted. The task of our function is to find the missing number and return it in linear time and constant space.

Since the array contains all the numbers from 0 to n but one, we can simply calculate the sum of all the elements of the array in linear time.

And then we can subtract it from the sum of first n natural numbers which can be calculated in constant time and space. The difference between the both will be our missing number.

Following is the code −

const arr = [3, 7, 8, 10, 11, 0, 2, 6, 1, 4, 5]; const findMissing = (arr = []) => { const sum = arr.reduce((acc, val) => acc + val); const { length: num } = arr; const correctSum = (num * (num + 1)) / 2; return diff = correctSum - sum; return diff; }; console.log(findMissing(arr));

Following is the console output −

9

- Related Questions & Answers
- Finding the majority element of an array JavaScript
- Finding the nth missing number from an array JavaScript
- Finding even length numbers from an array in JavaScript
- Finding the first redundant element in an array - JavaScript
- Find missing element in a sorted array of consecutive numbers in C++
- Find missing element in a sorted array of consecutive numbers in Python
- Finding sum of every nth element of array in JavaScript
- Detecting the largest element in an array of Numbers (nested) in JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript
- Finding degree of subarray in an array JavaScript
- Finding the missing number in an arithmetic progression sequence in JavaScript
- Finding all duplicate numbers in an array with multiple duplicates in JavaScript
- k-th missing element in an unsorted array in C++
- Finding missing letter in a string - JavaScript

Advertisements