See the original problem on HackerRank.
Solutions
A bruteforce approach consists in enumerating all possible combination of pairs and check if any contains all pairs with the same sum. Enumerating and checking all the combinations is clearly expensive.
Actually, there is only one possible combination that would satisfy the constraint and can be found directly.
Intuitively, suppose we are 4 people and we want to play together in pairs. To make the match balanced, we have to join the strongest with the weakest. That’s it. Same story here. To find a solution, first we need to sort the skills, then we combine the players taking one from the tail and another one from the head, iteratively:


Sort it:


Join players together:


Here is a C++ solution:


This is a trivial application of the twopointer technique.
Another way to see this problem is with zip:


In other words, we lazily form pairs of skills by summing together both the ends of the array, and then we find if all such sums are equal. Here is an example:


Sort it:


Zip with sum:


To check if the resulting range consists of all equal elements we can use adjacent_find
that is just a shorthand to check if all adjacent elements of a range satisfy a predicate. In this case, std::not_equal_to<>{}
. If we find any that is not equal to the following one, the constraint is broken.
Here is a Python succinct variant by Simone Santillo, Andrea Battistello and Francesco Solera:


Other solutions use data structures that allow fast retrieval or a simple frequency table. For example, Elia Giacobazzi and Andrea Naletto ended up with this snippet using Python’s Counter
:

