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.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
n == nums.length
1 <= n <= 10^5
n
is a multiple of 31 <= nums[i] <= 10^5
1 <= k <= 10^5
Solution
Method 1 – Greedy Grouping After Sorting
Intuition
By sorting the array, the closest numbers are adjacent. Grouping every three consecutive numbers ensures the minimum possible difference within each group. If the difference between the smallest and largest in any group exceeds k
, it’s impossible to form valid groups.
Approach
- Sort the input array
nums
. - Iterate through the sorted array in steps of 3.
- For each group of three, check if the difference between the first and third element is at most
k
. - If yes, add the group to the answer.
- If not, return an empty array (impossible to divide).
- Return the list of groups if all are valid.
Code
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
(due to sorting) - 🧺 Space complexity:
O(n)
(for the answer array)