Divide Array Into Arrays With Max Difference - Problem

Imagine you're a team captain dividing players into groups for a tournament! You have an array of n integers (where n is divisible by 3) and need to create exactly n/3 teams, each containing exactly 3 players.

Here's the challenge: within each team of 3, the difference between any two players' scores must not exceed k. This ensures balanced, competitive teams!

Your mission: Return a 2D array where each sub-array represents a valid team of 3 players. If it's impossible to form such balanced teams, return an empty array.

Example: With scores [1,3,3,2,7,3] and k=3, you could form teams like [[1,2,3],[3,3,7]] since within each team, no two scores differ by more than 3.

Input & Output

example_1.py โ€” Basic Valid Case
$ Input: nums = [1,3,3,2,7,3], k = 3
โ€บ Output: [[1,2,3],[3,3,7]]
๐Ÿ’ก Note: After sorting: [1,2,3,3,3,7]. First group [1,2,3] has max difference 3-1=2 โ‰ค 3. Second group [3,3,7] has max difference 7-3=4 > 3, so this would actually return [].
example_2.py โ€” Valid Grouping
$ Input: nums = [1,3,4,8,7,9,3,5,1], k = 2
โ€บ Output: [[1,1,3],[3,4,5],[7,8,9]]
๐Ÿ’ก Note: After sorting: [1,1,3,3,4,5,7,8,9]. Groups: [1,1,3] (diff=2), [3,4,5] (diff=2), [7,8,9] (diff=2). All differences โ‰ค k=2.
example_3.py โ€” Impossible Case
$ Input: nums = [1,2,3,4], k = 1
โ€บ Output: []
๐Ÿ’ก Note: Not enough elements (need multiple of 3). But if we had [1,2,3,10,11,12], the group [3,10,11] would have difference 11-3=8 > k=1, making it impossible.

Constraints

  • n == nums.length
  • 1 โ‰ค n โ‰ค 105
  • n is a multiple of 3
  • 1 โ‰ค nums[i] โ‰ค 105
  • 1 โ‰ค k โ‰ค 105

Visualization

Tap to expand
Tournament Team FormationUnsorted Players (by skill):731332Sort by skill levelSorted Players:123337Team 1: [1,2,3]Gap: 3-1=2 โ‰ค k=3 โœ“Team 2: [3,3,7]Gap: 7-3=4 > k=3 โœ—Tournament Impossible!Team 2 has too large skill gap
Understanding the Visualization
1
Line Up Players
Sort all players by skill rating from lowest to highest
2
Form Teams Greedily
Group every 3 consecutive players into a team
3
Check Team Balance
Ensure skill gap within each team doesn't exceed k
4
Validate Solution
If any team fails the balance check, tournament is impossible
Key Takeaway
๐ŸŽฏ Key Insight: Sorting enables greedy grouping - if consecutive elements can't form a valid team, no other arrangement will work either!
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 21
23.7K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen