Divide Array Into Arrays With Max Difference - Problem
You are given an integer array nums of size n where n is a multiple of 3 and a positive integer k.
Divide the array nums into n / 3 arrays of size 3 satisfying the following condition:
- The difference between any two elements in one array is less than or equal to
k.
Return a 2D array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return any of them.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,3,5,2,4,6], k = 2
›
Output:
[[1,2,3],[4,5,6]]
💡 Note:
After sorting: [1,2,3,4,5,6]. Group consecutively: [1,2,3] has max diff 3-1=2≤k, [4,5,6] has max diff 6-4=2≤k.
Example 2 — Impossible Case
$
Input:
nums = [1,3,3,2,7,3], k = 3
›
Output:
[]
💡 Note:
After sorting: [1,2,3,3,3,7]. First group [1,2,3] works (diff=2≤3), but second group [3,3,7] has diff=4>3, so return empty array.
Example 3 — All Same Elements
$
Input:
nums = [2,2,2,2,2,2], k = 0
›
Output:
[[2,2,2],[2,2,2]]
💡 Note:
All elements are identical, so max difference in any group is 0≤k=0. Any grouping works.
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
Input Array
Original array with n elements (multiple of 3) and constraint k
2
Sort & Group
Sort array and form consecutive triplets
3
Validate & Return
Check each group's max difference ≤ k, return result
Key Takeaway
🎯 Key Insight: Sorting first ensures that consecutive grouping minimizes differences within each group
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code