Divide Players Into Teams of Equal Skill - Problem
Divide Players Into Teams of Equal Skill

You are the coach of an esports tournament and need to organize n players into balanced teams! ๐ŸŽฎ

Given an array skill of even length n where skill[i] represents the skill level of the i-th player, your task is to:

1. Divide all players into exactly n/2 teams of size 2
2. Ensure each team has the same total skill sum
3. Calculate the chemistry of each team (product of both players' skills)
4. Return the sum of all team chemistries

If it's impossible to create teams with equal skill sums, return -1.

Example: With skills [3,2,5,1,3,4], you can form teams: (1,5), (2,4), (3,3). Each team sums to 6, and total chemistry = 1ร—5 + 2ร—4 + 3ร—3 = 22.

Input & Output

example_1.py โ€” Basic case with valid teams
$ Input: [3,2,5,1,3,4]
โ€บ Output: 22
๐Ÿ’ก Note: After sorting: [1,2,3,3,4,5]. Pairs: (1,5)=6, (2,4)=6, (3,3)=6. All sums equal 6. Chemistry = 1ร—5 + 2ร—4 + 3ร—3 = 5+8+9 = 22.
example_2.py โ€” Impossible case
$ Input: [3,4]
โ€บ Output: -1
๐Ÿ’ก Note: Only one possible team (3,4) with sum=7. Since there's only one team, equal sums are impossible (need at least 2 teams to compare).
example_3.py โ€” Simple valid case
$ Input: [1,1,2,3]
โ€บ Output: -1
๐Ÿ’ก Note: After sorting: [1,1,2,3]. Trying pairs: (1,3)=4 and (1,2)=3. Sums are different (4โ‰ 3), so return -1.

Constraints

  • 2 โ‰ค skill.length โ‰ค 105
  • skill.length is even
  • 1 โ‰ค skill[i] โ‰ค 1000

Visualization

Tap to expand
๐Ÿ† Optimal Team Formation StrategyInput: [3, 2, 5, 1, 3, 4]Goal: Form teams with equal skill sumsStep 1: Sort Players123345Sorted: Weakest โ†’ StrongestStep 2: Pair from Ends (Two Pointers)15Team 1: Sum=624Team 2: Sum=633Team 3: Sum=6โœ… All Teams Have Equal Sum = 6Chemistry = (1ร—5) + (2ร—4) + (3ร—3) = 5 + 8 + 9 = 22๐Ÿ’ก Key Insight: Pairing extremes in sorted array naturally creates balanced teams!
Understanding the Visualization
1
Sort by Skill
Arrange all players from weakest to strongest
2
Pair Extremes
Match the weakest available player with the strongest available player
3
Check Balance
Verify that all teams have the same total skill level
4
Calculate Chemistry
Sum up the chemistry (product of skills) for all valid teams
Key Takeaway
๐ŸŽฏ Key Insight: In a sorted array, if equal-sum pairs exist, pairing elements from opposite ends (smallest+largest, second-smallest+second-largest, etc.) always produces the optimal solution with O(n log n) time complexity.
Asked in
Microsoft 8 Amazon 6 Google 4 Meta 3
35.2K Views
Medium Frequency
~15 min Avg. Time
1.6K 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