Divide Players Into Teams of Equal Skill — LeetCode 2491 Python Solution

MediumArrayHash TableTwo PointersSorting
Problem
#2491
Reading time
2 min

The 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.

Example

Input
skill = [3,2,5,1,3,4]
Output
22
Explanation
Divide the players into the following teams: (1, 5), (2, 4), (3, 3), where each team has a total skill of 6.

Python solution

Python
class Solution:
    def dividePlayers(self, skill: List[int]) -> int:
        skill.sort()
        t = skill[0] + skill[-1]
        i, j = 0, len(skill) - 1
        ans = 0
        while i < j:
            if skill[i] + skill[j] != t:
                return -1
            ans += skill[i] * skill[j]
            i, j = i + 1, j - 1
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2491. Divide Players Into Teams of Equal Skill is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2491. Divide Players Into Teams of Equal Skill?
LeetCode 2491. Divide Players Into Teams of Equal Skill is rated Medium on LeetCode.
What is the time complexity of LeetCode 2491. Divide Players Into Teams of Equal Skill?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2491. Divide Players Into Teams of Equal Skill?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 2491. Divide Players Into Teams of Equal Skill cover?
LeetCode 2491. Divide Players Into Teams of Equal Skill is tagged Array, Hash Table, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview