#2966
Divide Array Into Arrays With Max Difference
MediumArrayGreedySortingGreedySortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution leverages sorting and a greedy approach. By sorting the array first, we can ensure that any three consecutive elements will have the smallest possible difference, making it easier to check the condition.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array.
- 2Step 2: Iterate through the sorted array in steps of 3, checking if the difference between the first and last element of each triplet is less than or equal to k.
- 3Step 3: If valid, add the triplet to the result; if not, return an empty array.
solution.py11 lines
1# Full working Python code
2
3def divide_array(nums, k):
4 nums.sort()
5 result = []
6 for i in range(0, len(nums), 3):
7 if nums[i + 2] - nums[i] > k:
8 return []
9 result.append([nums[i], nums[i + 1], nums[i + 2]])
10 return result
11ℹ
Complexity note: The sorting step takes O(n log n), and we iterate through the array in O(n), making this approach efficient.
- 1Sorting the array allows us to easily group elements with minimal differences.
- 2Using a greedy approach ensures that we can quickly check the conditions for triplets.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.