Created
May 4, 2024 06:58
-
-
Save rehas/086548c846ab46c150d003e3c0f6070c to your computer and use it in GitHub Desktop.
find-smallest-common-number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const findSmallestCommonNumber = function(inputArr1, inputArr2, inputArr3){ | |
let index1 = 0; | |
let index2 = 0; | |
let index3 = 0; | |
let currentMax = Number.MIN_VALUE; | |
// if we go overflow on any array we can stop the loop | |
while(index1 <inputArr1.length && index2 < inputArr2.length && index3<inputArr3.length){ | |
if(inputArr1[index1] === inputArr2[index2] && inputArr2[index2] == inputArr3[index3]){ | |
return inputArr1[index1]; | |
} | |
currentMax = Math.max(inputArr1[index1],inputArr2[index2],inputArr3[index3]); | |
if(inputArr1[index1] < currentMax){ | |
index1++; | |
} | |
if(inputArr2[index2] < currentMax){ | |
index2++; | |
} | |
if(inputArr3[index3] < currentMax){ | |
index3++; | |
} | |
} | |
// safely return -1 if we finish any of the arrays without a match. | |
return -1; | |
} | |
let inputArr1 = [1, 4, 6, 7, 8, 10, 14]; | |
let inputArr2 = [1, 4, 5, 6, 7, 8, 50]; | |
let inputArr3 = [0, 6, 7, 8, 10, 25, 30, 40]; | |
let res = findSmallestCommonNumber(inputArr1,inputArr2, inputArr3); | |
console.log(res); | |
inputArr1 = [1, 4, 6, 7, 8, 10, 14]; | |
inputArr2 = [1, 4, 5, 7, 8, 50]; | |
inputArr3 = []; | |
res = findSmallestCommonNumber(inputArr1,inputArr2, inputArr3); | |
console.log(res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment