Divide Players Into Teams of Equal Skill - Problem

You are given a positive integer array skill of even length n where skill[i] denotes the skill of the ith player.

Divide the players into n / 2 teams of size 2 such that the total skill of each team is equal.

The chemistry of a team is equal to the product of the skills of the players on that team.

Return the sum of the chemistry of all the teams, or return -1 if there is no way to divide the players into teams such that the total skill of each team is equal.

Input & Output

Example 1 — Basic Valid Case
$ Input: skill = [3,2,5,1,3,4]
Output: 22
💡 Note: Sort to [1,2,3,3,4,5]. Pair from ends: (1,5) sum=6 chemistry=5, (2,4) sum=6 chemistry=8, (3,3) sum=6 chemistry=9. Total: 5+8+9=22
Example 2 — Impossible Case
$ Input: skill = [3,4]
Output: 12
💡 Note: Only one possible pairing: (3,4). Team sum=7, chemistry=3×4=12. Since there's only one team, all teams have equal sums.
Example 3 — Cannot Form Equal Teams
$ Input: skill = [1,1,2,3]
Output: -1
💡 Note: Sort to [1,1,2,3]. Try pairing from ends: (1,3) sum=4, (1,2) sum=3. Team sums are not equal, so return -1.

Constraints

  • 2 ≤ skill.length ≤ 105
  • skill.length is even
  • 1 ≤ skill[i] ≤ 1000

Visualization

Tap to expand
Divide Players Into Teams of Equal Skill INPUT skill array (n=6 players) 3 i=0 2 i=1 5 i=2 1 i=3 3 i=4 4 i=5 After Sorting: 1 2 3 3 4 5 n = 6 players Teams needed: n/2 = 3 Total sum: 1+2+3+3+4+5 = 18 Target per team: 18/3 = 6 ALGORITHM STEPS 1 Sort Array Ascending order to pair smallest with largest 2 Calculate Target target = totalSum / teams target = 18 / 3 = 6 3 Two Pointer Pairing Pair i with n-1-i Check sum equals target 4 Sum Chemistry chemistry = skill[i] * skill[n-1-i] Team Pairings: 1 + 5 = 6 chemistry: 1*5 = 5 2 + 4 = 6 chem: 2*4 = 8 3 + 3 = 6 chem: 3*3 = 9 FINAL RESULT Formed Teams: Team 1 1 + 5 = 6 Team 2 2 + 4 = 6 Team 3 3 + 3 = 6 Chemistry Sum: 5 + 8 + 9 = 22 Output: 22 Key Insight: After sorting, pair the smallest skill with the largest skill (two-pointer approach). If all pairs have equal sum, valid teams exist. Sum all products for total chemistry. Time: O(n log n) for sorting | Space: O(1) extra space TutorialsPoint - Divide Players Into Teams of Equal Skill | Optimal Solution (Two Pointer)
Asked in
Meta 15 Amazon 12 Google 8
23.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen