Leetcode 2966: Divide Array Into Arrays With Max Difference

grid47
grid47
Exploring patterns and algorithms
Jan 15, 2024 7 min read

You are given an array nums of size n where n is a multiple of 3, and a positive integer k. Your task is to divide the array into n / 3 subarrays, each containing exactly 3 elements, such that the difference between the largest and smallest element in each subarray is less than or equal to k. If it’s possible to divide the array in this way, return a 2D array containing the subarrays. If it is not possible, return an empty array. If multiple valid divisions exist, return any valid one.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array `nums` of size `n` and an integer `k`. The array is divisible by 3 to allow division into valid groups of three elements.
Example: nums = [1, 3, 4, 8, 7, 9, 3, 5, 1], k = 2
Constraints:
• n == nums.length
• 1 <= n <= 10^5
• n is a multiple of 3
• 1 <= nums[i] <= 10^5
• 1 <= k <= 10^5
Output: Return a 2D array containing the subarrays formed by grouping the elements, where each group contains exactly 3 elements, and the difference between the maximum and minimum element in each group is at most `k`. If this is not possible, return an empty array.
Example: [[1, 1, 3], [3, 4, 5], [7, 8, 9]]
Constraints:
Goal: The goal is to divide the array into subarrays of size 3 where the difference between the maximum and minimum integers in each group is less than or equal to `k`.
Steps:
• Sort the array `nums` in ascending order.
• Iterate through the sorted array and try to form subarrays of size 3.
• For each subarray, check if the difference between the largest and smallest element is less than or equal to `k`.
• If all subarrays are valid, return them; otherwise, return an empty array.
Goal: The size of the array is guaranteed to be divisible by 3. Each subarray must contain exactly three elements, and the difference between the largest and smallest element in each subarray must be at most `k`.
Steps:
• 1 <= n <= 10^5
• n is a multiple of 3
• 1 <= nums[i] <= 10^5
• 1 <= k <= 10^5
Assumptions:
• The array can always be divided into groups of three, as long as the division criteria are met.
• The order of the elements within each subarray can vary, as long as the condition on the difference between the max and min is satisfied.
Input: Input: nums = [1, 3, 4, 8, 7, 9, 3, 5, 1], k = 2
Explanation: The array is first sorted as [1, 1, 3, 3, 4, 5, 7, 8, 9]. The valid subarrays are [[1, 1, 3], [3, 4, 5], [7, 8, 9]]. The difference between the maximum and minimum elements in each subarray is at most 2, so the output is valid.

Input: Input: nums = [2, 4, 2, 2, 5, 2], k = 2
Explanation: It is impossible to create valid subarrays because one subarray will always have the elements 2 and 5, and 5 - 2 = 3, which is greater than `k = 2`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus