JS Interview - Calculating Differences - Question 16

preview_player
Показать описание
This episode shows how you can calculate the largest relative difference between any two numbers inside an Array.

Full Interview playlist:

Рекомендации по теме
Комментарии
Автор

​ Steve Griffith Converting the array to a Set will also result in O(n) time complexity.. Because Set will also have to traverse the complete Array. We can find the solution in O(n).

function biggestDifference(array){
let min = Number.MAX_VALUE;
let max = Number.MIN_VALUE;
if(array.length === 0) return;
if(array.length === 1) return array[0];
array.forEach(num => {
if(num > max){
max = num;
}
if(num < min){
min = num;
}
});
return max - min;
}

_jayant
Автор

let difference = (function (arr) {
let higth = arr.reduce( (a, b) => a > b ? a : b )
let low = arr.reduce( (a, b) => a < b ? a : b )
return higth - low
})

levlubentsov
Автор

Thank You! Will you make more of these videos?

jadeyu
Автор

I wrote a function that first checks if we got array as argument, and then check if all values are numbers. I came up with this. Please let me know how you would do it...



        throw new Error(`Expected an array,  got ${numbers.constructor.name} instead!`);
    }

    numbers.forEach(n => {


        }
    })



}

demian
Автор

question: why is function(a, b){ return b-a) is dirty, and how to write it properlerier?

Horoe
Автор

Why would an ajax login request fail while it has the correct login credential .... i tried it with curl and it worked why it didn't with ajax ?

mnageh-bomm
Автор

I think converting the array into set and vice-versa to remove duplicates step is unnecessary. That's because we are going to sort the things in the end and a[0] will always be least and a[len -1] as max.

gyanendra_chaubey
Автор

I don't think we need to remove duplicates. It will work just fine if you take difference between highest and lowest numbers with duplicates.

arunaveerappan
Автор

why do we use b - a, rather than a -b ? :)

MrMarkgyuro
Автор

with for Loop

let big = [];
let small = [arr[0]];

for (let i = 0; i < arr.length; i++) {
if (arr[i] > big) {
big = arr[i];
} else if (arr[i] < small) {
small = arr[i];
}
}

return big - small;

iali