Following approaches works on small number of arrays but when I try large volume then it is timing out. What is the best way to check all numbers are equal in large volume of arrays?
In below sample, I am confirming which numbers are uniform between given numbers where it works for small volume (i.e., 1 - 300) but not doing well for large volume (i.e., 1 - 999999999999)
References:
using .every
const uniformInteger = (A, B) => {
let output = 0;
for (let i = A; i <= B; i++) {
const reversed = i.toString().split("").reverse();
// Option - 1 = using .every
if (reversed.every((val, i, arr) => val === arr[0])) {
output++;
}
}
return output;
};
console.log(uniformInteger(1, 300));
// Timed out
// console.log(uniformInteger(1, 999999999999));
using Set
const uniformInteger = (A, B) => {
let output = 0;
for (let i = A; i <= B; i++) {
const reversed = i.toString().split("").reverse();
// Option - 2 = using Set
if (new Set(reversed).size == 1) {
output++;
}
}
return output;
};
console.log(uniformInteger(1, 300));
using another loop to check current and next value
function identical(array) {
for (var i = 0; i < array.length - 1; i++) {
if (array[i] !== array[i + 1]) {
return false;
}
}
return true;
}
const uniformInteger = (A, B) => {
let output = 0;
for (let i = A; i <= B; i++) {
const reversed = i.toString().split("").reverse();
// Option - 3 = another loop to check current and next value
if (identical(reversed)) {
output++;
}
}
return output;
};
console.log(uniformInteger(1, 300));