I want to iterate an array and find all pairs where their difference is 2
This is what i have so far:
var numberOfCases = 5;
var diff = 2;
var input = [1,5,3,4,2];
getPossiblepairs(input);
function getPossiblepairs(input){
for(cmp in input){
for(number in input){
if((input[cmp] - input[number]) == diff){
console.log("("+input[cmp]+","+input[number]+")");
}
}
}
}
This works but i still feel guilty using two for loops as the bigO is O(n^2) Is this the only way to do this?
You can do this in O(n log n). Sort the array then go through it in a single pass. Find the difference between the current element and each of the next two, printing out the pair if one is different by 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With