LeetCode 1296: Divide Array in Sets of K Consecutive Numbers Solution
Master LeetCode problem 1296 (Divide Array in Sets of K Consecutive Numbers), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1296. Divide Array in Sets of K Consecutive Numbers
Problem Explanation
Explanation:
To solve this problem, we can use a hashmap to store the frequencies of each number in the input array nums. We then iterate through the keys of the hashmap in ascending order, and for each key, we check if there are enough occurrences of consecutive numbers starting from that key to form sets of size k.
- Create a hashmap
freqMapto store the frequencies of each number innums. - Sort the keys of
freqMap. - For each key in the sorted keys:
- If the frequency of the current key in
freqMapis greater than 0:- Check if there are enough occurrences of consecutive numbers starting from the current key to form sets of size
k. - If yes, reduce the frequencies of those consecutive numbers in
freqMap. - If no, return false.
- Check if there are enough occurrences of consecutive numbers starting from the current key to form sets of size
- If the frequency of the current key in
- If we successfully iterate through all keys, return true.
Time Complexity: O(n log n) where n is the size of nums (due to sorting)
Space Complexity: O(n) where n is the size of nums
Solution Code
import java.util.*;
class Solution {
public boolean isPossibleDivide(int[] nums, int k) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
List<Integer> keys = new ArrayList<>(freqMap.keySet());
Collections.sort(keys);
for (int key : keys) {
int freq = freqMap.get(key);
if (freq > 0) {
for (int i = 0; i < k; i++) {
if (freqMap.getOrDefault(key + i, 0) < freq) {
return false;
}
freqMap.put(key + i, freqMap.get(key + i) - freq);
}
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1296 (Divide Array in Sets of K Consecutive Numbers)?
This page provides optimized solutions for LeetCode problem 1296 (Divide Array in Sets of K Consecutive Numbers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1296 (Divide Array in Sets of K Consecutive Numbers)?
The time complexity for LeetCode 1296 (Divide Array in Sets of K Consecutive Numbers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1296 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1296 in Java, C++, or Python.