Divide Arr Into Arrs With Max Diff
divide-array-into-arrays-with-max-difference
Date created: 2025-02-25-Tue 11:11
Question Description
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.
Example 1:
Input: nums = [1,3,4,8,7,9,3,5,1]
, k = 2
Output: [[1,1,3],[3,4,5],[7,8,9]]
Explanation:
The difference between any two elements in each array is less than or equal to 2.
Example 2:
Input: nums = [2,4,2,2,5,2]
, k = 2
Output: []
Explanation:
Different ways to divide nums into 2 arrays of size 3 are:
[[2,2,2],[2,4,5]] (and its permutations)
[[2,2,4],[2,2,5]] (and its permutations)
Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since 5 - 2 = 3 > k, the condition is not satisfied and so there is no valid division.
Example 3:
Input: nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11]
, k = 14
Output: [[2,2,12],[4,8,5],[5,9,7],[7,8,5],[5,9,10],[11,12,2]]
Explanation:
The difference between any two elements in each array is less than or equal to 14.
Constraints:
n == nums.length
1 <= n <= 105
n is a multiple of 3
1 <= nums[i] <= 105
1 <= k <= 105
problem link solution video link
Thought Process
You are given an integer array nums of size n where n is a multiple of 3 and a positive integer k.
Info 1
: \( n \ge 3 \)- we can check and see that the length of example’s input are always a multiple of 3
- thoughts: we can find all subarrays with group 3, emm using backtracking, but the input list is too long for that, \( 3^k \) is large
Observations
:- the output is sorted
Code
class Solution:
def divideArray(self, nums: List[int], k: int) -> List[List[int]]:
nums.sort() # this can help group the values which are close together
res = []
for i in range(0, len(nums), 3):
# make sure we have at least 3 elements in the subarray
# check the endpoint of the subarray
# check if the difference between the last and first element is less than k
if nums[i + 2] - nums[i] > k:
return []
# actual logic
res.append(nums[i:i+3]) # note need to include the 3rd one
return res
Time/Space Complexity
Time: \( O(nlogn) \) for looping and sorting the array
Space: \( O(n) \) since the output stores \( n/3 \) groups, each containing 3 elements; the total space required for result
is \( O(n) \) in the worst case