We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Divide Array Into Arrays With Max Difference

Number: 3241

Difficulty: Medium

Paid? No

Companies: Google


Problem Description

Given an integer array nums of length n (where n is a multiple of 3) and a positive integer k, divide nums into n/3 subarrays of size 3. Each subarray must satisfy the condition that the difference between any two of its elements is at most k. Return any valid 2D array of subarrays if it exists, otherwise return an empty array.


Key Insights

  • Sorting the array minimizes the differences between adjacent elements.
  • After sorting, a simple greedy strategy is to form groups of 3 consecutive elements.
  • For each group, check if the difference between the maximum and minimum element is less than or equal to k.
  • If any group does not satisfy the condition, it is impossible to form a valid grouping.
  • The sorted order is optimal for minimizing the differences, so if a valid triple grouping exists, it will be found this way.

Space and Time Complexity

Time Complexity: O(n log n) due to sorting the array. Space Complexity: O(n) for storing the result (ignoring sorting overhead).


Solution

The algorithm begins by sorting the nums array. Sorting ensures that consecutive elements are as close as possible, minimizing potential differences in any contiguous block. Once sorted, we iterate through the array in steps of 3. For each triple, we check if the difference between the largest (last) and smallest (first) element is at most k. If every triple satisfies this constraint, we output the array of triples; otherwise, we return an empty array. This approach is greedy and works because the smallest differences occur between consecutive elements in a sorted list. The main trick is to recognize that if any valid grouping exists, the optimal way (i.e., the grouping with minimum differences) is to utilize the sorted order.


Code Solutions

# Python solution with line-by-line comments

def divideArray(nums, k):
    # Sort the array to minimize the differences between consecutive numbers
    nums.sort()
    result = []
    n = len(nums)
    
    # Iterate through the sorted list in chunks of 3
    for i in range(0, n, 3):
        # Extract a triple (group of three numbers)
        triple = nums[i:i+3]
        # Check if the difference between max and min in the triple is within the allowed range k
        if triple[-1] - triple[0] > k:
            return []  # Return empty array if condition fails for any triple
        # Otherwise, add the valid triple to the result
        result.append(triple)
    
    return result

# Example test
print(divideArray([1,3,4,8,7,9,3,5,1], 2))
← Back to All Questions