Divide Array in Sets of K Consecutive Numbers Problem
Description
LeetCode Problem 1296.
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. Otherwise, return false.
Example 1:
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].
Example 2:
Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
Example 3:
Input: nums = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.
Constraints:
1 <= k <= nums.length <= 10^51 <= nums[i] <= 10^9
Note: This question is the same as 846: https://leetcode.com/problems/hand-of-straights/
Solution
Approach: Greedy From the Smallest Number
If the length of nums is not a multiple of k, the answer is false straight away. Otherwise count how many times each number appears.
Look at the smallest number x that is still left, with count c. It cannot be in the middle or at the end of a run, since there is nothing smaller to come before it, so every one of its c copies must start a run x, x + 1, ..., x + k - 1. That forces us to take c copies of each of those numbers. If any of them has fewer than c copies left, no division exists; otherwise subtract c from each and continue with the next smallest number that still has copies.
Going through the distinct values in sorted order processes exactly these "smallest remaining" numbers; values whose count already dropped to 0 are skipped. Only numbers that start runs do the inner k steps, and there are at most n / k runs, so the inner loops add up to O(n).
Complexity: O(n log n) time for sorting the distinct values and O(n) space for the counts.
from collections import Counter
class Solution:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
if len(nums) % k:
return False
cnt = Counter(nums)
for x in sorted(cnt):
c = cnt[x]
if c == 0:
continue
# x is the smallest number left, so c runs must start at x: x .. x + k - 1.
for y in range(x, x + k):
if cnt[y] < c:
return False
cnt[y] -= c
return True