1296. Divide Array in Sets of K Consecutive Numbers

1296. Divide Array in Sets of K Consecutive Numbers #

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. 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 <= 100000
  • 1 <= nums[i] <= 1000000000

Problem Summary #

Given an integer array nums and a positive integer k, determine whether this array can be divided into sets consisting of k consecutive numbers. If possible, return true; otherwise, return false.

Solution Approach #

Greedy algorithm

  • Sort nums in ascending order
  • Count the numbers in nums using a hash map (key: number, value: count)
  • Iterate through the numbers in nums, using numbers with a count greater than 1 as the start of consecutive numbers, and look for the subsequent elements of the consecutive numbers. If k consecutive numbers cannot be found, return false
  • If all numbers can find k consecutive numbers, return true

##Code

package leetcode

import "sort"

func isPossibleDivide(nums []int, k int) bool {
	mp := make(map[int]int)
	for _, v := range nums {
		mp[v] += 1
	}
	sort.Ints(nums)
	for _, num := range nums {
		if mp[num] == 0 {
			continue
		}
		for diff := 0; diff < k; diff++ {
			if mp[num+diff] == 0 {
				return false
			}
			mp[num+diff] -= 1
		}
	}
	return true
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文