Divide Array in Sets of K Consecutive Numbers in Python


Given an array of integers 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].


1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
1 <= k <= nums.length


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] <= 0:
      for index in range(1, k):
        count_map[num+index] -= count_map[num]
        if count_map[num+index] < 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))

Leave a reply:

Your email address will not be published.