Divide Array in Sets of K Consecutive Numbers in Python
1 min read

Divide Array in Sets of K Consecutive Numbers in Python

Problem:

Given an array of integer nums and a positive integer k, find whether it’s possible to divide this array into sets of k consecutive numbers. Return True if its possible otherwise return False.

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

Constraints:

1 <= nums.length <= 10^5

1 <= nums[i] <= 10^9

1 <= k <= nums.length

Solution:

class Solution:
  def isPossibleDivide(nums, k):
    from collections import Counter

    count_map = Counter(nums)
    for num in sorted(count_map.keys()):
      if count_map[num] &lt;= 0:
        continue
      for index in range(1, k):
        count_map[num+index] -= count_map[num]
        if count_map[num+index] &lt; 0:
          return False
    return True


num_list = [1,2,3,3,4,4,5,6]
positive_num = 4
print(Solution.isPossibleDivide(num_list, positive_num))