Python 2491.py
class Solution:
def dividePlayers(self, skill: List[int]) -> int:
result = 0
size = len(skill)
teams = size // 2
# all teams need equal total skill
total = sum(skill)
if total % teams != 0:
return -1 # impossible
total //= teams
skill.sort()
for i in range(teams):
# match the lowest and highest player
a = skill[i]
b = skill[-i - 1]
if a + b != total:
return -1 # impossible
# chemistry
result += a * b
return result
Difficulty
and has an acceptance rate of about 69% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Sorting
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The dividePlayers method receives a list of integer skill values and attempts to form pairs of players such that every pair has the same combined skill. If such a pairing is possible, the method returns the sum of the products of the skills in each pair (the “chemistry” of the teams). When the required uniform total cannot be achieved, the method returns -1 to indicate impossibility.
Key Steps
Determining the number of teams
size = len(skill)
teams = size // 2
The code computes the total number of players and derives the number of teams by integer division, implicitly handling the case where the list length is odd because the subsequent logic will detect an impossible configuration.
Verifying that a uniform team total is feasible
total = sum(skill)
if total % teams != 0:
return -1 # impossible
total //= teams
Here the sum of all skill values is calculated. The remainder check ensures that the total skill can be evenly divided among the required number of teams; if not, the function exits early. When the division is exact, the target sum for each team is stored back in total.
Sorting the skill list
skill.sort()
Sorting arranges the skill values in non-decreasing order, which enables a deterministic pairing strategy that pairs the smallest remaining skill with the largest remaining skill.
Pairing players and accumulating chemistry
for i in range(teams):
a = skill[i]
b = skill[-i - 1]
if a + b != total:
return -1 # impossible
result += a * b
The loop iterates exactly teams times. In each iteration the i-th smallest element (a) and the i-th largest element (b) are selected. The sum of the two is compared against the pre-computed target total. If any pair fails to meet the target, the function aborts with -1. When the pair is valid, the product of the two skills is added to result, accumulating the total chemistry.
Returning the final result
return result
After all pairs have been validated and their chemistry summed, the accumulated value is returned.
Edge Cases Handled
When the input list contains an odd number of elements, the integer division size // 2 yields a team count that is insufficient to pair every player. The subsequent check total % teams != 0 will fail because the total skill cannot be evenly distributed among a non-integral number of teams, causing the method to return -1.
If the sum of all skills is not divisible by the number of teams, the early modulus test catches the inconsistency before any sorting or pairing occurs, preventing unnecessary work.
During the pairing loop, any mismatch between the sum of the current lowest and highest remaining skills and the required uniform total triggers an immediate return of -1. This guards against scenarios where the sorted order still cannot produce equal-sum pairs, such as when skill values are unevenly distributed despite an overall divisible total.
The algorithm also implicitly handles duplicate skill values because the sorted order groups identical values together, and the pairing logic treats each occurrence independently.
Performance Optimizations
The method performs a single pass to compute the total skill, avoiding repeated aggregation. By checking the divisibility condition early, it eliminates the need for sorting and pairing when the problem is unsolvable, saving both time and memory.
Sorting is executed only once, providing an ordered structure that enables the two-pointer style pairing without additional data structures. The loop accesses elements directly by index from both ends of the list, which is an O(1) operation per access, ensuring that the pairing step runs in linear time relative to the number of teams.
The use of integer division (//) for both the team count and the target team total eliminates floating-point overhead and guarantees exact arithmetic, which is particularly beneficial for large integer inputs.
By accumulating the chemistry directly into the result variable inside the loop, the code avoids the creation of intermediate collections, keeping the memory footprint minimal.
Overall, the combination of early exit conditions, a single sort, and in-place calculations yields an efficient solution that scales well with the size of the input list.
ELI5 - Simplified Explanation
Imagine you have a big group of children who want to play a game in pairs. Each child has a specific skill number. To make the game fair, every pair needs to have the exact same total skill level when you add their two numbers together.
First, the code looks at all the children and finds the total skill level of everyone combined. It divides that total by the number of pairs to find out exactly what number each team should add up to. If it turns out that some children are left over or the math does not work out perfectly, the game cannot happen.
Next, the code lines up all the children from the ones with the lowest skill to the ones with the highest skill. To make the teams, it takes the child with the smallest number and the child with the largest number to form the first pair. Then it takes the next smallest and next largest to form the next pair, and so on until everyone is grouped.
As the code makes each pair, it checks if their two skill numbers add up to the target total. If any pair adds up to a different number, then it is not a valid way to play. If every pair does add up correctly, the code multiplies the two numbers of each pair together to find their chemistry score and adds that to a growing pile of points.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | Java | C++ | Python | TS | |||
| WalkCCC | Java | C++ | Python | |||||
| leetcode.ca | JS | Java | C++ | Go | Python | Rust | TS | |
| Progiez | Java | C++ | Python | |||||
| github | charles-wangkai | Java | ||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| varunu28 | Java | |||||||
| withaarzoo | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| varunu28 | Java | |||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 1679: Max Number of K-Sum Pairs
Solved On The Same Day
- problem 1287: Element Appearing More Than 25% In Sorted Array
- problem 2363: Merge Similar Items
- problem 2418: Sort the People
- problem 2441: Largest Positive Integer That Exists With Its Negative
- problem 2506: Count Pairs Of Similar Strings
- problem 2716: Minimize String Length
- problem 2744: Find Maximum Number of String Pairs
- problem 2374: Node With Highest Edge Score
- problem 2442: Count Number of Distinct Integers After Reverse Operations
- problem 2554: Maximum Number of Integers to Choose From a Range I
- problem 2780: Minimum Index of a Valid Split
- problem 2933: High-Access Employees
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality