Problem 2491

Abstract / Summary

Divide players into teams so each team has the same total skill level.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
25 lines | 633 bytes | submitted December 11, 2023 | GitHub   29% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.88 | σ = 0.85

Complexity Analysis

Time: loglinear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
23 links | 10 authors | 7 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

13 solutions   December 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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