Divide Array Into Arrays With Max Difference — LeetCode 2966 Python Solution

MediumGreedyArraySorting
Problem
#2966
Pattern
Greedy
Reading time
2 min

The problem

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.

Python solution

Python
class Solution:
    def divideArray(self, nums: List[int], k: int) -> List[List[int]]:
        nums.sort()
        ans = []
        n = len(nums)
        for i in range(0, n, 3):
            t = nums[i : i + 3]
            if t[2] - t[0] > k:
                return []
            ans.append(t)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2966. Divide Array Into Arrays With Max Difference is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2966. Divide Array Into Arrays With Max Difference?
LeetCode 2966. Divide Array Into Arrays With Max Difference is rated Medium on LeetCode.
What is the time complexity of LeetCode 2966. Divide Array Into Arrays With Max Difference?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2966. Divide Array Into Arrays With Max Difference?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2966. Divide Array Into Arrays With Max Difference cover?
LeetCode 2966. Divide Array Into Arrays With Max Difference is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview