This should work with complexity n log n:
function getPossiblepairs(input, diff){ // Create a copy of the original array, so it is not affected by the next operation var sortedInput = input.slice(); // Sort the array sortedInput.sort(); // Iterate through the array, starting from the 0th element for (var i=0, n=sortedInput.length; i<n; i++){ firstNumber = sortedInput[i]; // Iterate through the array, starting from the (i+1)th element for (var j=i+1; j<n && sortedInput[j] <= firstNumber + diff; j++){ secondNumber = sortedInput[j]; // if it matches, then log it! if (secondNumber - firstNumber == diff){ console.log('(' + firstNumber + ', ' + secondNumber + ')'); } } } }
See this post for more on array duplication.
For use and testing see: http://jsfiddle.net/gycjup5u/2/
source share