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
Divide Array Into Arrays With Max Difference INPUT nums = [1,3,5,2,4,6] 1 3 5 2 4 6 k = 2 (max difference allowed) n = 6 (multiple of 3) Need: 6/3 = 2 arrays Each array: size 3 Goal: Split into arrays of 3 where max - min <= k in each array ALGORITHM (Greedy) 1 Sort Array [1,2,3,4,5,6] 1 2 3 4 5 6 2 Group by 3s Take consecutive triplets 3 Check Condition arr[2] - arr[0] <= k [1,2,3]: 3-1=2 <= 2 OK [4,5,6]: 6-4=2 <= 2 OK 4 Return Result All groups valid Sorted + consecutive = minimal difference within each group FINAL RESULT 2D Array Output: Array 1: [1, 2, 3] 1 2 3 Array 2: [4, 5, 6] 4 5 6 [[1,2,3],[4,5,6]] Verification: Both arrays: max diff = 2 2 <= k(2) -- OK Key Insight: Sorting ensures adjacent elements have minimal differences. By grouping every 3 consecutive elements, we minimize the max-min difference in each group. If sorted[i+2] - sorted[i] > k for any group, no solution exists. TutorialsPoint - Divide Array Into Arrays With Max Difference | Greedy Approach Time: O(n log n) for sorting | Space: O(n) for result array
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
23.4K 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