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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code