#2491

Divide Players Into Teams of Equal Skill

Medium
ArrayHash TableTwo PointersSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution leverages sorting and pairing the weakest player with the strongest player. This ensures that we can form teams with equal skill sums efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the skill array.
  2. 2Step 2: Pair the first element with the last, the second with the second last, and so on.
  3. 3Step 3: Calculate the total chemistry based on these pairs.
solution.py14 lines
1# Full working Python code
2
3def divide_players(skill):
4    skill.sort()
5    n = len(skill)
6    target_sum = sum(skill) // (n // 2)
7    chemistry_sum = 0
8
9    for i in range(n // 2):
10        if skill[i] + skill[n - 1 - i] != target_sum:
11            return -1
12        chemistry_sum += skill[i] * skill[n - 1 - i]
13
14    return chemistry_sum

Complexity note: The time complexity is O(n log n) due to the sorting step. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1Pairing the weakest and strongest players maximizes the chance of equal skill sums.
  • 2Sorting the array allows for efficient pairing and validation of team sums.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.