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:
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.
Example 1:
Input: nums = [1,3,4,8,7,9,3,5,1], k = 2
Output: [[1,1,3],[3,4,5],[7,8,9]]
Explanation:
The difference between any two elements in each array is less than or equal to 2.
Example 2:
Input: nums = [2,4,2,2,5,2], k = 2
Output: []
Explanation:
Different ways to divide nums into 2 arrays of size 3 are:
Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since 5 - 2 = 3 > k, the condition is not satisfied and so there is no valid division.
Example 3:
Input: nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14
Output: [[2,2,12],[4,8,5],[5,9,7],[7,8,5],[5,9,10],[11,12,2]]
Explanation:
The difference between any two elements in each array is less than or equal to 14.
Constraints:
n == nums.length1 <= n <= 105n is a multiple of 31 <= nums[i] <= 1051 <= k <= 105Problem Overview: You are given an integer array nums and a value k. The goal is to divide the array into groups of exactly three elements such that the difference between the maximum and minimum value in each group is at most k. If forming such groups for the entire array is impossible, return an empty array.
Approach 1: Sorting and Forming Groups (Time: O(n log n), Space: O(1) extra)
The key observation: if three numbers can form a valid group, they will be closest together in sorted order. Start by sorting the array using a standard sorting algorithm. Then iterate through the sorted list in steps of three and check whether nums[i+2] - nums[i] ≤ k. Since the array is sorted, nums[i] is the minimum and nums[i+2] is the maximum in that group. If the difference exceeds k, no valid grouping exists because any other combination would only increase the gap. Otherwise, add the three numbers as one group and continue.
This works because sorting clusters close values together, ensuring that if a valid triplet exists, it will appear consecutively. The algorithm performs a single pass after sorting, making it efficient and easy to implement.
Approach 2: Greedy Two-Pointer Technique (Time: O(n log n), Space: O(1))
This approach also starts by sorting the array, then applies a greedy grouping strategy using pointer movement. After sorting, treat the array as a sequence of candidates. Use a pointer i to mark the start of the next group and greedily attempt to include the next two elements (i+1 and i+2). If the difference between the smallest and largest values in this window is within k, record the group and advance the pointer by three.
If the difference exceeds k, a valid grouping is impossible because any later element will only increase the difference. Sorting ensures that the smallest feasible combination is checked first. This greedy reasoning relies on the ordered structure of the array and avoids unnecessary comparisons.
The technique demonstrates how greedy decisions combined with array traversal can solve grouping problems efficiently. Once sorted, each element is processed exactly once.
Recommended for interviews: The sorting + grouping approach is what most interviewers expect. It shows you recognize that ordering simplifies the constraint max - min ≤ k. A brute force attempt would involve checking combinations of three elements, which is inefficient. Sorting first and validating consecutive triplets demonstrates strong algorithmic intuition and leads directly to the optimal O(n log n) solution.
Sort the array to ensure that the smallest numbers are adjacent, making it easier to form groups where the maximum difference is less than or equal to k. After sorting, iterate through the array and try to form groups of three. At each step, check if the difference between the first and third numbers in the potential group is less than or equal to k. If yes, form the group; otherwise, return an empty array as it's impossible to meet the requirement.
This C solution first sorts the array using qsort. It then iterates through the sorted array, forming groups of three numbers and ensuring that the difference between the smallest and largest number in each group is ≤ k. If a valid group cannot be formed, it returns 0 indicating failure.
Time Complexity: O(n log n), due to the sorting step.
Space Complexity: O(1), as no additional space is used beyond the input and output storage.
This approach uses a greedy technique with two pointers to form groups of three elements. Sort the array first. Maintain two pointers, &&&i&&& and &&&j&&&, where &&&i&&& points to the start of a possible group and &&&j&&& iterates over the array to form a group when the criteria are met. When the triplet satisfies the requirement, move to the next possible group.
This C implementation uses a sorted array and a two-pointer technique. Pointers &&&i&&& and &&&j&&& are used to track possible triplets. The solution evaluates whether formed groups satisfy the maximum difference ≤ k. If a triplet exceeds the maximum difference, it raises an error and exits as formation is impractical.
Time Complexity: O(n log n) for sorting, O(n) for the two pointers traversal, making it O(n log n).
Space Complexity: O(n) due to allocated space for the resulting groups.
| Approach | Complexity |
|---|---|
| Sorting and Forming Groups | Time Complexity: O(n log n), due to the sorting step. |
| Greedy Two-Pointer Technique | Time Complexity: O(n log n) for sorting, O(n) for the two pointers traversal, making it O(n log n). |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sorting and Forming Groups | O(n log n) | O(1) | Best general solution. Sorting ensures closest values are grouped first. |
| Greedy Two-Pointer Technique | O(n log n) | O(1) | Useful when implementing greedy window grouping after sorting. |
Divide Array Into Arrays With Max Difference - Leetcode 2966 - Python • NeetCodeIO • 13,729 views views
Watch 9 more video solutions →Practice Divide Array Into Arrays With Max Difference with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor