5

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?

5
  • There may be algorithms you can do to get better, if you actually know the distribution of numbers (here they are a sequential series, although out of order). But with just 5 entries, so 25 iterations O(5^2), do you really care to get it more efficient than that? Commented Nov 30, 2014 at 9:05
  • I changed the wording to ask for other methods, as 'best way' is going to be closed as primarily opinion based. Commented Nov 30, 2014 at 9:06
  • 2
    Sort the list whuch is O(N) log n. The one that has a differencee of two from the current one is either the next element, or the one after that. That's an O(1) check. Checking all of them is O(N). So overall O(N log N) Commented Nov 30, 2014 at 9:09
  • @Paul that only works if the numbers aren't repeated Commented Nov 30, 2014 at 9:11
  • 1
    Another O(N) Pass to put equal elements into counted buckets would fix that. Commented Nov 30, 2014 at 9:12

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

what he said. beat me by a minute
@Doug i'm currently trying to implementing your solution, but wouldn't the difference between each next two element always remain 1 ?
Hi @Pizzy213codes, with your example, after the sort phase there'd be [1, 2, 3, 4, 5]. The first step is to compare 1 to 2 and 1 to 3. The diff is 1 in the first case, 2 in the second. If there were any non-consecutive numbers like [1, 5, 7, 22], then the differences will get bigger. I'm guessing you figured it out, though!
4

This should work with a n log n complexity:

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 information about the array duplication.

For usage and testing, see: http://jsfiddle.net/gycjup5u/2/

14 Comments

That's order n^2. And worse than the original in run time (it does length^2 comparions, like the original, but sorts as well)
Yeah, my (corrected) typo was totally worth a "-1".
That;s still n^2. So, yes, it was
No it isn't. The second iteration starts at i+1!
Edited with the extra condition, and changed my -1 to +1 (since your answer did give code...)
|
3

do you have memory for a copy of the array? Sort it first, O(n log n), then pick out the pairs in a single O(n) pass.

Comments

2

You can use indexOf() method for every element to determine if an array contains the element greater than given by diff:

function getPossiblePairs(input, diff) {
    for(i in input) {
        var n = input.indexOf(input[i] + diff);
        if(n != -1) {
            console.log("(" + input[i] + "," + input[n] + ")");
        }
    }
}

getPossiblePairs(input, diff);

2 Comments

Which is, of course, O(N^2). So the OP will still feel guilty :)
@Paul yes, this is my fault, didn't notice the optimization request, just thought of another way of doing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.