RE: #1 Programmer challenge

You are viewing a single comment's thread from:

#1 Programmer challenge

in programmer •  7 years ago  (edited)

My thought:

As you iterate through the array, store the difference between the given number and array element in memory. If an element you come across in the array is in the set already, you've found a pair. Might be easier to see in code:

(In java since that's what I primarily use)

    int[] arr = { 5, 10, 5, 15, 20, 5 };
    int n = 20;
    int count = 0;
    HashMap<Integer, Integer> diffs = new HashMap<>();
    for (Integer i : arr) {
        if (diffs.containsKey(i)) {
            count += diffs.get(i);
        }
        Integer found = diffs.getOrDefault(n - i, 0);
        diffs.put(n - i, ++found);
    }

    System.out.println("count: " + count);

Note: I had to use a HashMap and not a HashSet because HashSet doesn't account for several of the same number in the array (eg. 5 which you see in my case above).

Edit: I think I solved the wrong problem, since you specified all pairs and not the count of pairs. Dunno where that came from. Easy enough to fix though, you just store both numbers as you find them and output that instead.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!