Possible to use Math.min to get second smallest number from array? - javascript

I am using Math.min to get the smallest number out of an array of numbers. However, I also need to get the second smallest number as well. Wondering if there is a way to do this using Math.min as well, otherwise looking for the best way to get this number.
Here's what I have:
var arr = [15, 37, 9, 21, 55];
var min = Math.min.apply(null, arr.filter(Boolean));
var secondMin; // Get second smallest number from array here
console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);

just to make that thread completed: the fastest way is to iterate all the elements just like you can do to find minimum. But up to your needs there will be two variables used: first minimum (candidate) and second one.
This logic is O(N) while sorting approach is O(N lg(N)).
But maybe you shouldn't care if this is just for practice.
In case repeatition should be processed as independant value(just like it would be for .sort(...)[1]) then it should <= be used instead of <.
var arr = [15, 37, 9, 21, 55];
var min = Infinity, secondMin = Infinity;
for (var i= 0; i< arr.length; i++) {
if (arr[i]< min) {
secondMin = min;
min = arr[i];
} else if (arr[i]< secondMin) {
secondMin = arr[i];
}
}
console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);

I see you are using Array.filter (but why?) on your first min. So, if we are using ES6 features you can find the second lowest value by first removing min from the array.
var secondMin = Math.min.apply(null, arr.filter(n => n != min));
edit: for clarity, unless you are doing something very clever with Array.filter(Boolean) while calculating the first min, you should just pass it the array without filtering:
var min = Math.min.apply(null, arr);

If you are not worried about performance you could simply sort the array.
arr.sort(function(a, b) {
return a - b;
});

#skyboyer provides what is probably the fastest algorithm for finding the two smallest elements. Another type algorithm that runs in O(n) time is selection (in the general comp-sci definition, not how it is normally used in JavaScript), which will find the kth smallest element of an array and separate the elements into those larger and those smaller than the kth.
Even though most partitioning selection algorithms (quickselect, Floyd-Rivest, introselect) run in O(n) time, #skyboyer's answer will be faster because of the specific nature of the partition you are looking for, and because all those algorithms come with a heavy constant factor.
There is a javascript library implementing Floyd-Rivest, but named quickselect that can do the partitioning for you, in place:
quickselect(arr, 1)
arr will be rearranged so that arr[0] is the minimum, arr[1] is the second smallest element, and the remaining elements are in some arbitrary order.

ES6 solution with reduce (very performant) 🚀
const A = [8, 24, 3, 20, 1, 17]
const min = Math.min(...A)
const secondMin = A.reduce((pre, cur) => (cur < pre && cur !== min) ? cur : pre
, Infinity)
console.log(min, secondMin)

This the #skyboyer version that will handle repeats correctly:
function secondSmallest(x) {
if (x.length < 2) return 0;
let first = Number.MAX_VALUE;
let second = Number.MAX_VALUE;
for (let i = 0; i < x.length; i++) {
let current = x[i];
if (current < first) {
second = first;
first = current;
} else if (current < second && current !== first) {
second = current;
}
}
return second;
}
console.log(secondSmallest([1, 1, 1, 1, 2]));
console.log(secondSmallest([1, 2, 1, 1, 1]));
console.log(secondSmallest([6, 3, 4, 8, 4, 5]));

var arr=[1,1,1,1,1,-1,-2];
var firstmin=arr[0];
var secondmin=arr[1];
for(i=0;i<=arr.length;i++){
if(arr[i]<firstmin){
secondmin=firstmin;
firstmin=arr[i];
}else if(i>=1 && arr[i]<secondmin) {
secondmin=arr[i];
}
}
console.log(firstmin);
console.log(secondmin);`

var arr=[1,0,-1,-2,-8,5];
var firstmin=arr[0];
var secondmin=arr[1];
for(i=0;i<=arr.length;i++) {
if(arr[i]<firstmin){
secondmin=firstmin;
firstmin=arr[i];
}
else if(i>=1 && arr[i]<secondmin) {
secondmin=arr[i];
}
}
console.log(firstmin);
console.log(secondmin);
var arr = [15, 37, 9, 21, 55];
var min = Infinity, secondMin = Infinity;
for (var i= 0; i< arr.length; i++) {
if (arr[i]< min) {
secondMin = min;
min = arr[i];
} else if (arr[i]< secondMin) {
secondMin = arr[i];
}
}
console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);

A recursive approach with ternary operators would look like this. If the array has duplicates it would give you a non duplicated second min.
For example if you have have [1, 1, 2] the second min would be 2 not 1.
function findMinimums(arr, min, secondMin, i) {
if (arr.length === i) {
return {
min,
secondMin
}
}
return findMinimums(
arr,
min = arr[i] < min ? arr[i] : min,
arr[i] < secondMin && min !== arr[i] ? arr[i] : secondMin,
++i
)
}
const arr = [5, 34, 5, 1, 6, 7, 9, 2, 1];
console.log(findMinimums(arr, arr[0], arr[1], 0))

var arr = [15, 37, 9, 21, 55];
const [secondMin, min] = arr.sort((a,b) => b - a).slice(-2)
console.log('Smallest number: ' + min);
console.log('Second smallest number: ' + secondMin);

function secondSmallest(arr){
let firstSmallest = Infinity, secondSmallest = Infinity;
// if the length is 1; return the element
if(arr.length == 1){
return arr[0]
}
for (let i= 0; i< arr.length; i++) {
if (arr[i]< firstSmallest) {
secondSmallest = firstSmallest;
firstSmallest = arr[i];
} else if (arr[i]< secondSmallest) {
secondSmallest = arr[i];
}
}
console.log(firstSmallest, secondSmallest)
return secondSmallest
}

function findTwoSmallestNumbersFromArray(num) {
let min = Math.min(...num)
let secondMin = Math.min(...num.filter(numbers => !min.toString().includes(numbers)))
console.log(min, secondMin)
}

Yes, it's possible. But rather than directly using Math.min() we have to use Math.min.apply(), as we know Math.min() wouldn't take an array. Here's the solution which will work even if there's duplicates of smallest number in the array.
const findSecondSmallest = function (arr) {
const smallest = Math.min.apply(null, arr);
/*
To remove duplicates too I compared the smallest number through loop.
Otherwise You can direcly set the value of smallest element to 'Infinity'
like this-
arr[arr.indexOf(smallest)] = Infinity;
*/
for (let i = 0; i < arr.length; i++) {
if (smallest === arr[i]) {
arr[i] = Infinity;
}
}
const secondSmallest = Math.min.apply(null, arr);
return secondSmallest;
};
console.log(findSecondSmallest([3, 3, 3, 5, 5, 7, 9, 11, 13])); //5

The Best way to get the second minimum value from an array.
let array = [5, 8, 3, 8, 2, 6, 7, 10, 2];
let minValue = Math.min(...array);
let secondMinVAlue = Math.min(...array.filter((v) => v !== minValue));
console.log(secondMinVAlue);

let num = [4,12,99,1,3,123,5];
let sort = num.sort((a,b) => {return a-b})
console.log(sort[1])

Related

How can I return "1-5" if the array is [1,2,3,4,5] in JavaScript?

I am trying to make a program that returns ["1-5"] if I give [1,2,3,4,5].
I have made it but I can't filter it. So I want a code that will filter my output code. Or any code that is better than mine.
let array = [1,2,3,5,6,7,8,10,11, 34, 56,57,];
let x = [];
for(let i = 0; i < array.length; i++){
for(let j = 0; j < array.length; j++){
if(array[i] + j == array[j]){
x.push(array[i] + "-" + array[j]);
}
if(array[j] > array[i] + j && array[j + 1]){
let y = array.slice(j, array.length)
array = y;
i, j = 0;
}
if(array[i] - array[i + 1] != -1 && array[i + 1] - array[i] != 1 && array[i + 1] != undefined){
x.push(array[i]);
}
}
}
console.log(x);
The phrasing of the question makes this somewhat difficult to answer, but based on your code snippet I can gather that you are either:
Attempting to find the range of the entire array OR
Attempting to find contiguous ranges within the array
Based on these interpretations, you could answer this question as follows:
function detectRange(a) {
// clone a
const b = [...a]
// remove first value
const min = max = b.splice(0, 1)[0]
// compute range
const range = b.reduce(({min, max}, i) => {
if(i < min) min = i
if(i > max) max = i
return { min, max }
}, {min, max})
return range
}
function detectRanges(a) {
// clone a
const b = [...a]
// remove first value
const min = max = b.splice(0, 1)[0]
// init ranges array
const ranges = [ ]
// compute ranges
const range = b.reduce(({min, max}, i) => {
if(i === max + 1) {
return {min , max: i}
} else {
ranges.push({min, max})
return {min: i, max: i}
}
}, {min, max})
// push the remaining range onto the array
ranges.push(range)
return ranges
}
function printRange(r) {
console.log(`["${r.min}-${r.max}"]`)
}
function printRanges(r) {
r.forEach(i => {
printRange(i)
})
}
// detect and print range of whole array
printRange(detectRange([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))
// detect and print only contiguous ranges within array
printRanges(detectRanges([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))
If you assume that the list is sorted, we only need to traverse the list sequentially. There's no need to have double-nested loops. If you maintain sufficient states, you can determine whether you are in a group and you merely manage the start versus the last element in the group.
To simplify things I made use of ES6 string interpolation ${start}-${last}.
let array = [1,2,3,5,6,7,8,10,11, 34, 56,57];
let result = [ ];
let hasStart = false;
let start = 0;
let last = 0;
for (let num of array) {
if (!hasStart) {
hasStart = true;
last = start = num;
continue;
}
if (num === last + 1) {
last = num;
continue;
}
result.push( start === last ? start : `${start}-${last}` );
last = start = num;
}
if (hasStart) {
result.push( start === last ? start : `${start}-${last}` );
}
console.log(result);
Input: [1,2,3,4,5]
Output: ["1-5"]
So I assume you want to get string in format:
["smallestelement-largestelement"]
var input1 = [1,2,3,4,5]
console.log( "["+'"'+Math.min(...input1)+"-"+Math.max(...input1)+'"'+"]")
If what you want is string in format:
["firstelement-lastelement"]
var input1 = [1,2,3,4,5]
console.log( "["+'"'+input1[0]+"-"+input1.pop()+'"'+"]")
If you have an integer array, and if you want to output the range, you could natively sort() it (you can also provide rules for sorting) and use shift() for the first element and slice(-1) for the last:
let arr = [4,1,5,3].sort();
console.log(arr.shift()+'-'+arr.slice(-1));
As said in the comments, you should clarify if you wish "1-57" for the snippet array, or describe your use case more broadly.
const array = [1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57];
let s = null;
const result = array.sort((a, b) => a - b).reduce((p, c, i, arr) => {
if (!s) s = c;
if (c + 1 !== arr[i + 1]) {
p.push(s === c ? s : `${s}-${c}`);
s = null;
}
return p
}, [])
console.log(result);

My nested for loop times out when searching for 2 numbers in an array that add up to a sum value

I'm trying to find a better/faster algorithm that doesn't timeout when I try to find any 2 numbers in an array of numbers that add up to a sum(ex. s). I need to return the pair of numbers that adds up to sum(s) which also have the indices that appear the earliest(there maybe many other pairs). Here is my nested for loop approach.
function sum(ints, s){
let pusher = [];
let count = 1000;
for(let i = 0; i < ints.length; i++){
for(let j = i+1; j < ints.length; j++){
if(ints[i] + ints[j] === s){
if(j < count){
pusher = [ints[i],ints[j]];
count = j;
}
}
}
}
return pusher.length > 0 ? pusher : undefined ;
}
To reduce the computational complexity from O(n ^ 2) to O(n), create a Setinstead. When iterating over a number, check if the set has the value sum - num - if it does, return that pair as the result. Otherwise, put the number into the Set:
Or you could use a Set
function sum(ints, sum) {
const set = new Set();
for (const num of ints) {
const otherNum = sum - num;
if (set.has(otherNum)) {
return [num, otherNum];
} else {
set.add(num);
}
}
}
console.log(sum([3, 4, 99, -2, 55, 66, -3], 1));
console.log(sum([1, 9, 15, 2, 4, 7, 5], 6));

Find the biggest number in an array by using JavaScript loops

Create a function called biggestNumberInArray().
That takes an array as a parameter and returns the biggest number.
Here is an array
const array = [-1, 0, 3, 100, 99, 2, 99]
What I try in my JavaScript code:
function biggestNumberInArray(arr) {
for (let i = 0; i < array.length; i++) {
for(let j=1;j<array.length;j++){
for(let k =2;k<array.length;k++){
if(array[i]>array[j] && array[i]>array[k]){
console.log(array[i]);
}
}
}
}
}
It returns 3 100 99.
I want to return just 100 because it is the biggest number.
Is there a better way to use loops to get the biggest value?
Using three different JavaScript loops to achieve this (for, forEach, for of, for in).
You can use three of them to accomplish it.
Some ES6 magic for you, using the spread syntax:
function biggestNumberInArray(arr) {
const max = Math.max(...arr);
return max;
}
Actually, a few people have answered this question in a more detailed fashion than I do, but I would like you to read this if you are curious about the performance between the various ways of getting the largest number in an array.
zer00ne's answer should be better for simplicity, but if you still want to follow the for-loop way, here it is:
function biggestNumberInArray (arr) {
// The largest number at first should be the first element or null for empty array
var largest = arr[0] || null;
// Current number, handled by the loop
var number = null;
for (var i = 0; i < arr.length; i++) {
// Update current number
number = arr[i];
// Compares stored largest number with current number, stores the largest one
largest = Math.max(largest, number);
}
return largest;
}
There are multiple ways.
Using Math max function
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(Math.max(...array))
Using reduce
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(array.reduce((element,max) => element > max ? element : max, 0));
Implement our own function
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
function getMaxOutOfAnArray(array) {
let maxNumber = -Infinity;
array.forEach(number => { maxNumber = number > maxNumber ? number : maxNumber; })
console.log(maxNumber);
}
getMaxOutOfAnArray(array);
The simplest way is using Math.max.apply:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
return Math.max.apply(Math, arr);
}
console.log(biggestNumberInArray(array));
If you really want to use a for loop, you can do it using the technique from this answer:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
var m = -Infinity,
i = 0,
n = arr.length;
for (; i != n; ++i) {
if (arr[i] > m) {
m = arr[i];
}
}
return m;
}
console.log(biggestNumberInArray(array));
And you could also use reduce:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(array) {
return array.reduce((m, c) => c > m ? c : m);
}
console.log(biggestNumberInArray(array));
I think you misunderstand how loops are used - there is no need to have three nested loops. You can iterate through the array with a single loop, keeping track of the largest number in a variable, then returning the variable at the end of the loop.
function largest(arr) {
var largest = arr[0]
arr.forEach(function(i) {
if (i > largest){
largest = i
}
}
return largest;
}
Of course you can do this much more simply:
Math.max(...arr)
but the question does ask for a for loop implementation.
This is best suited to some functional programming and using a reduce, for loops are out of favour these days.
const max = array => array && array.length ? array.reduce((max, current) => current > max ? current : max) : undefined;
console.log(max([-1, 0, 3, 100, 99, 2, 99]));
This is 70% more performant than Math.max https://jsperf.com/max-vs-reduce/1
Another visual way is to create a variable called something like maxNumber, then check every value in the array, and if it is greater than the maxNumber, then the maxNumber now = that value.
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
let maxNumber;
for(let i = 0; i < arr.length; i++){
if(!maxNumber){ // protect against an array of values less than 0
maxNumber = arr[i]
}
if(arr[i] > maxNumber){
maxNumber = arr[i];
}
}
return maxNumber
}
console.log(biggestNumberInArray(array));
I hope this helps :)
var list = [12,34,11,10,34,68,5,6,2,2,90];
var length = list.length-1;
for(var i=0; i<length; i++){
for(j=0; j<length; j++){
if(list[j]>list[j+1]){
[ list[j] , list[j+1] ] = [ list[j+1] , list[j] ];
}
}
}
console.log(list[list.length-1]);
You Can try My codes to find the highest number form array using for loop.
function largestNumber(number){
let max = number[0];
for(let i = 0; i < number.length; i++){
let element = number[i];
if(element > max){
max = element;
}
}
return max;
}
let arrayNum= [22,25,40,60,80,100];
let result = largestNumber(arrayNum);
console.log('The Highest Number is: ',result);
let arr = [1,213,31,42,21];
let max = 0;
for(let i = 0; i < arr.length; i++) {
if(arr[i] > max) {
max = arr[i]
}
}
console.log(max)
There are multiple ways.
way - 1 | without for loop
const data = [-1, 0, 3, 100, 99, 2, 99];
// way - 1 | without for loop
const maxValue = Math.max(...data);
const maxIndex = data.indexOf(maxValue);
console.log({ maxValue, maxIndex }); // { maxValue: 100, maxIndex: 3 }
way - 2 | with for loop
const data = [-1, 0, 3, 100, 99, 2, 99];
// way - 2 | with for loop
let max = data[0];
for (let i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
console.log(max); // 100
THis is the simple function to find the biggest number in array with for loop.
// Input sample data to the function
var arr = [-1, 0, 3, 100, 99, 2, 99];
// Just to show the result
console.log(findMax(arr));
// Function to find the biggest integer in array
function findMax(arr) {
// size of array
let arraySize = arr.length;
if (arraySize > 0) {
// Initialize variable with first index of array
var MaxNumber = arr[0];
for (var i = 0; i <= arraySize; i++) {
// if new number is greater than previous number
if (arr[i] > MaxNumber) {
// then assign greater number to variable
MaxNumber = arr[i];
}
}
// return biggest number
return MaxNumber;
} else {
return 0;
}
}
You can try this if you want to practice functions
const numbs = [1, 2, 4, 5, 6, 7, 8, 34];
let max = (arr) => {
let max = arr[0];
for (let i of arr) {
if (i > max) {
max = i;
}
}
return max;
};
let highestNumb = max(numbs);
console.log(highestNumb);
const array = [-1, 0, 3, 100, 99, 2, 99]
let longest = Math.max(...array);
what about this
const array = [1, 32, 3, 44, 5, 6]
console.time("method-test")
var largestNum = array[0]
for(var i = 1; i < array.length; i++) {
largestNum = largestNum > array[i] ? largestNum : array[i]
}
console.log(largestNum)
console.timeEnd("method-test")

Finding the next largest number in an array using JavaScript If...Else Statements

Would you be so kind and explain how "else if" statement in the below piece of code returns the second largest number from an array?
Especially that there is no AND operator (&&) within "else if statement". I mean for ex.:
else if (max2 < array[i] && max1 > array[i])
I found people using this kind of approach on stackOverflow but they did not give any detailed explanations ("why it works"):
var arr1 = [2, 3, 1, 6, 100, 49, 5, 7, 8, 9];
function getSecondMaxNumber(array) {
var max1 = 0;
var max2 = 0;
for (var i = 0; i <= array.length; i++) {
if (max1 < array[i]) {
max1 = array[i];
} else if (max2 < array[i]) {
max2 = array[i];
}
}
return max2;
}
console.log(getSecondMaxNumber(arr1));
UPDATE
The above method is wrong as Hassan commented below.
I decided to use:
var arr1 = [2, 3, 1, 6, 100, 49, 5, 7, 8, 9];
function getSecondMaxNumber(array) {
function sortNumbers(a, b) { //Compare numbers.
return a - b;
}
var arrSorted = array.sort(sortNumbers); //Set up sorting.
return arrSorted[arrSorted.length - 2]; //Choose the second largest number in an array.
}
console.log(getSecondMaxNumber(arr1)); //Show me that number.
You don't need the && because the if condition has already eliminated the possibility of max1 being less than array[i]. You can't get to the else if condition without the if first failing.
And side note, the loop condition should be < instead of <=.
if (max1 < array[i]) {
If the current number is bigger then the current biggest number, set that number to the biggest number.
} else if (max2 < array[i]) {
If its not the biggest number it may be the second biggest.
Maybe shorter:
const result = array.reduce(([max, max2], el) => el > max ? [el, max] : el > max2 ? [max, el] : [max, max2], [0,0])[1];

Find Missing Numbers from Unsorted Array

I found this JavaScript algorithm excercise:
Question:
From a unsorted array of numbers 1 to 100 excluding one number, how will you find that number?
The solution the author gives is:
function missingNumber(arr) {
var n = arr.length + 1,
sum = 0,
expectedSum = n * (n + 1) / 2;
for (var i = 0, len = arr.length; i < len; i++) {
sum += arr[i];
}
return expectedSum - sum;
}
I wanted to try and make it so you can find multiple missing numbers.
My solution:
var someArr = [2, 5, 3, 1, 4, 7, 10, 15]
function findMissingNumbers(arr) {
var missingNumbersCount;
var missingNumbers = [];
arr.sort(function(a, b) {
return a - b;
})
for(var i = 0; i < arr.length; i++) {
if(arr[i+1] - arr[i] != 1 && arr[i+1] != undefined) {
missingNumbersCount = arr[i+1] - arr[i] - 1;
for(j = 1; j <= missingNumbersCount; j++) {
missingNumbers.push(arr[i] + j)
}
}
}
return missingNumbers
}
findMissingNumbers(someArr) // [6, 8, 9, 11, 12, 13, 14]
Is there a better way to do this? It has to be JavaScript, since that's what I'm practicing.
You could use a sparse array with 1-values at indexes that correspond to values in the input array. Then you could create yet another array with all numbers (with same length as the sparse array), and retain only those values that correspond to an index with a 1-value in the sparse array.
This will run in O(n) time:
function findMissingNumbers(arr) {
// Create sparse array with a 1 at each index equal to a value in the input.
var sparse = arr.reduce((sparse, i) => (sparse[i]=1,sparse), []);
// Create array 0..highest number, and retain only those values for which
// the sparse array has nothing at that index (and eliminate the 0 value).
return [...sparse.keys()].filter(i => i && !sparse[i]);
}
var someArr = [2, 5, 3, 1, 4, 7, 10, 15]
var result = findMissingNumbers(someArr);
console.log(result);
NB: this requires EcmaScript2015 support.
The simplest solution to this problem
miss = (arr) => {
let missArr=[];
let l = Math.max(...arr);
let startsWithZero = arr.indexOf(0) > -1 ? 0 : 1;
for(i = startsWithZero; i < l; i++) {
if(arr.indexOf(i) < 0) {
missArr.push(i);
}
}
return missArr;
}
miss([3,4,1,2,6,8,12]);
Something like this will do what you want.
var X = [2, 5, 3, 1, 4, 7, 10, 15]; // Array of numbers
var N = Array.from(Array(Math.max.apply(Math, X)).keys()); //Generate number array using the largest int from X
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;}); //Return the difference
};
console.log(N.diff(X));
Option 1:
1. create a binary array
2. iterate over input array and for each element mark binary array true.
3. iterate over binary array and find out numbers of false.
Time complexity = O(N)
Space complexity = N
Option 2:
Sort input array O(nLogn)
iterate over sorted array and identify missing number a[i+1]-a[i] > 0
O(n)
total time complexity = O(nlogn) + O(n)
I think the best way to do this without any iterations for a single missing number would be to just use the sum approach.
const arr=[1-100];
let total=n*(n+1)/2;
let totalarray=array.reduce((t,i)=>t+i);
console.log(total-totalarray);
You can try this:
let missingNum= (n) => {
return n
.sort((a, b) => a - b)
.reduce((r, v, i, a) =>
(l => r.concat(Array.from({ length: v - l - 1 }, _ => ++l)))(a[i - 1]),
[]
)
}
console.log(missingNum([1,2,3,4,10]));
Solution to find missing numbers from unsorted array or array containing duplicate values.
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
var array1 = [1, 3, 4, 7, 9];
var n = array1.length;
var totalElements = array1.max(); // Total count including missing numbers. Can use max
var d = new Uint8Array(totalElements)
for(let i=0; i<n; i++){
d[array1[i]-1] = 1;
}
var outputArray = [];
for(let i=0; i<totalElements; i++) {
if(d[i] == 0) {
outputArray.push(i+1)
}
}
console.log(outputArray.toString());
My solution uses the same logic as trincot's answer
The time complexity is O(n)
const check_miss = (n) => {
let temp = Array(Math.max(...n)).fill(0);
n.forEach((item) => (temp[item] = 1));
const missing_items = temp
.map((item, index) => (item === 0 ? index : -1))
.filter((item) => item !== -1);
console.log(missing_items);
};
n = [5, 4, 2, 1, 10, 20, 0];
check_miss(n);

Categories

Resources