Similar Problems

Similar Problems not available

Divide Players Into Teams Of Equal Skill - Leetcode Solution


LeetCode:  Divide Players Into Teams Of Equal Skill Leetcode Solution

Difficulty: Medium

Topics: hash-table sorting array two-pointers  

Problem: Given n players with their skill level represented as an array, divide the players into two teams of equal size such that the difference between their total skill levels is minimum. Return the difference.

Example: Input: skills = [1,4,2,3,4,5,6,7] Output: 1 Explanation: There are two ways to form teams of equal size: Team1: [1,2,3,4] => Total skill level = 10 Team2: [4,5,6,7] => Total skill level = 22 Difference = 22-10 = 12 Team1: [1,4,5,6] => Total skill level = 16 Team2: [2,3,4,7] => Total skill level = 16 Difference = 16-16 = 0 Thus, the minimum difference is 0

Solution: Approach: To divide the players into two teams with equal skill level, we can use brute force in which we consider each possible pair of teams and find the difference in their total skill level. The pair with the minimum difference is the answer. However, this approach is not efficient as the time complexity for this solution is O(2^n) where n is the number of players. Hence, we need to optimize the above approach.

Let’s assume that the total skill level of all players is S. Therefore, the skill level of one team should be S/2 and the other team should also have a skill level of S/2. Based on this observation, we can use a binary search approach to find the teams such that their skill level is closest to S/2.


  1. Sort the skill array in descending order.
  2. Initialize the minimum difference to infinity and also initialize the current difference to 0.
  3. Set left pointer to 0 and right pointer to n-1.
  4. While left pointer is less than right pointer a. Calculate the middle point as (left+right)/2. b. Divide the array into two teams, the first team consists of the first half of the sorted skill levels up to the middle point, the second team consists of the second team. c. Calculate the difference in the total skill level of the two teams. If it is less than the current difference, update the current difference. d. If the total skill level of the first team is less than S/2, move the left pointer to the middle+1 point, else if it is greater, move the right pointer to the middle-1 point.
  5. Return the current minimum difference.

Time Complexity: Sorting the array takes O(nlogn) time. The binary search takes O(logn) time. At each iteration of the binary search, we calculate the total skill level of two teams, which takes O(n) time as we need to iterate through the array. Hence, the time complexity of this algorithm is O(nlogn).

Space Complexity: No extra space is used, thus the space complexity of this algorithm is O(1).


Divide Players Into Teams Of Equal Skill Solution Code