← Home

1296. Divide Array in Sets of K Consecutive Numbers

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
129

This is one of those problems where the clean idea matters more than the amount of code. For 1296. Divide Array in Sets of K Consecutive Numbers, the solution in this repository is mainly a greedy solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • erase while iterating
  • TLE
  • 36 / 39 test cases passed.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are isPossibleDivide.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//erase while iterating
02//TLE
03//36 / 39 test cases passed.
04class Solution {
05public:
06    bool isPossibleDivide(vector<int>& nums, int k) {
07        int N = nums.size();
08        if(N % k != 0) return false;
09        int times = N/k;
10        
11        sort(nums.begin(), nums.end());
12        
13        while(times-- > 0){
14            int smallest = nums[0];
15            for(int i = smallest; i < smallest + k; i++){
16                auto it = find(nums.begin(), nums.end(), i);
17                if(it != nums.end()){
18                    nums.erase(it);
19                }else{
20                    return false;
21                }
22            }
23        }
24        
25        return true;
26    }
27};
28
29//not erasing, sort each partition while iterating
30//TLE
31//36 / 39 test cases passed.
32class Solution {
33public:
34    bool isPossibleDivide(vector<int>& nums, int k) {
35        int N = nums.size();
36        if(N % k != 0) return false;
37        int times = N/k;
38        int cursor = 0;
39        
40        sort(nums.begin(), nums.end());
41        
42        // for(int num : nums){
43        //     cout << num << " ";
44        // }
45        // cout << endl;
46        
47        while(times-- > 0){
48            //sort each part division before
49            sort(nums.begin()+cursor, nums.end());
50            // for(auto it = nums.begin()+cursor; it != nums.begin()+cursor+k; it++){
51            //     cout << *it << " ";
52            // }
53            // cout << endl;
54            int smallest = nums[cursor];
55            for(int i = smallest; i < smallest + k; i++){
56                // cout << i << endl;
57                if(nums[cursor] != i){
58                    auto it = find(nums.begin()+cursor, nums.end(), i);
59                    if(it == nums.end()) return false;
60                    // cout << "finding " << i << ", swap " << cursor << " and " << it-nums.begin() << endl;
61                    swap(nums[it-nums.begin()], nums[cursor]);
62                }
63                cursor++;
64            }
65        }
66        
67        return true;
68    }
69};
70
71//optimized by using map(map is ordered by key)
72//Runtime: 440 ms, faster than 5.11% of C++ online submissions for Divide Array in Sets of K Consecutive Numbers.
73//Memory Usage: 27.9 MB, less than 100.00% of C++ online submissions for Divide Array in Sets of K Consecutive Numbers.
74//time: O(NlogN), map is sorted and each lookup takes O(logN)
75//space: O(N)
76class Solution {
77public:
78    bool isPossibleDivide(vector<int>& nums, int k) {
79        int N = nums.size();
80        if(N % k != 0) return false;
81        int times = N/k;
82        map<int, int> counter;
83        map<int, int>::iterator it;
84        
85        for(int num : nums){
86            counter[num]++;
87        }
88        
89        while(times > 0){
90            it = counter.begin();
91            int smallest = it->first;
92            int freq = it->second;
93            for(int i = smallest; i < smallest + k; i++){
94                if(counter.find(i) != counter.end() && counter[i] >= freq){
95                    counter[i]-=freq;
96                    if(counter[i] == 0) counter.erase(i);
97                }else{
98                    return false;
99                }
100            }
101            times-=freq;
102        }
103        
104        return true;
105    }
106};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.