MediumNo. 1296

Divide Array in Sets of K Consecutive Numbers — LeetCode 1296 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Hash Table, Sorting
Reading time
2 min

The problem

Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers. Return true if it is possible.

Example

Input
nums = [1,2,3,3,4,4,5,6], k = 4
Output
true
Explanation
Array can be divided into [1,2,3,4] and [3,4,5,6].

Python solution

PythonSolution
class Solution:
    def isPossibleDivide(self, nums: List[int], k: int) -> bool:
        if len(nums) % k:
            return False
        cnt = Counter(nums)
        for x in sorted(nums):
            if cnt[x]:
                for y in range(x, x + k):
                    if cnt[y] == 0:
                        return False
                    cnt[y] -= 1
        return True

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 1296. Divide Array in Sets of K Consecutive Numbers is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

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

Related problems

Related problems
No.ProblemDifficulty
0621Task SchedulerMedium
0632Smallest Range Covering Elements from K ListsHard
0846Hand of StraightsMedium
0954Array of Doubled PairsMedium
1054Distant BarcodesMedium
1090Largest Values From LabelsMedium

Frequently asked questions

How hard is LeetCode 1296. Divide Array in Sets of K Consecutive Numbers?

LeetCode 1296. Divide Array in Sets of K Consecutive Numbers is rated Medium on LeetCode.

What is the time complexity of LeetCode 1296. Divide Array in Sets of K Consecutive Numbers?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 1296. Divide Array in Sets of K Consecutive Numbers?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1296. Divide Array in Sets of K Consecutive Numbers cover?

LeetCode 1296. Divide Array in Sets of K Consecutive Numbers is tagged Greedy, Array, Hash Table 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.