Split an array into groups of three so that the maximum minus minimum in every group is within a given limit.
You are given an integer array and an integer . Your task is to divide the array into groups of exactly three elements each.
For every group, let be the smallest element and be the largest element in that group. The group is valid only if .
Return the groups if it is possible to partition all elements into valid groups; otherwise, indicate that no valid partition exists.
A common way to reason about this problem is to sort the array and then form groups from adjacent elements, but the exact validity must still be checked against the constraint.
Input Format
- An integer array
nums - An integer
k
Assume all elements of nums must be used exactly once.
Output Format
- Return a list of groups of size
3if a valid partition exists - Otherwise return an empty result / failure indication, depending on the platform formulation
Constraints
- All elements must be partitioned into groups of exactly 3
- Each group must satisfy
max(group) - min(group) <= k - Use every array element exactly once
Example 1
Input
nums = [1,2,3,4,5,6], k = 2
Output
[[1,2,3],[4,5,6]]
Explanation
Both groups have maximum difference 2, so the partition is valid.
Example 2
Input
nums = [1,3,5,8,9,10], k = 1
Output
[]
Explanation
No way exists to split all numbers into triples where each triple has max-min at most 1.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.