Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sorting
Greedy
Divide Array Into Arrays With Max Difference

Split an array into groups of three so that the maximum minus minimum in every group is within a given limit.

Acceptance 100%
Problem Statement

You are given an integer array and an integer kk. Your task is to divide the array into groups of exactly three elements each.

For every group, let min\min be the smallest element and max\max be the largest element in that group. The group is valid only if maxmink\max - \min \le k.

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 3 if 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
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.