MediumNo. 2966

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

Pattern
Greedy
Topics
Greedy, Array, Sorting
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

PythonSolution
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

Time
O(n × log n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
2971Find Polygon With the Largest PerimeterMedium
0179Largest NumberMedium
0324Wiggle Sort IIMedium
0452Minimum Number of Arrows to Burst BalloonsMedium
0455Assign CookiesEasy
0502IPOHard

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 × 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.

Free to download. Check it runs on your machine, then pick a plan.