A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1590. Make Sum Divisible by P, the solution in this repository is mainly a backtracking solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. 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: backtracking.
The notes already sitting in the source point us in the right direction:
- BFS
- TLE
- 127 / 142 test cases passed.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are backtrack, minSubarray.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- The queue gives the solution a level-by-level or frontier-style traversal.
- 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:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
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
01//BFS
02//TLE
03//127 / 142 test cases passed.
04class Solution {
05public:
06 void backtrack(vector<int>& nums, int& p, int start, long long& cursum, int rem, int& minrem){
07 if(cursum % p == 0){
08 minrem = min(minrem, rem);
09 }else{
10 int n = nums.size();
11 for(int i = start; i < n; ++i){
12 cursum -= nums[i];
13 backtrack(nums, p, i+1, cursum, rem+1, minrem);
14 cursum += nums[i];
15 }
16 }
17 };
18
19 int minSubarray(vector<int>& nums, int p) {
20 int n = nums.size();
21
22 long long total = accumulate(nums.begin(), nums.end(), 0LL);
23
24 if(total % p == 0){
25 return 0;
26 }
27
28 queue<pair<int, long long>> q;
29
30 for(int i = 0; i < n; ++i){
31 q.push({i, nums[i]});
32 }
33
34 int remlen = 1;
35
36 while(!q.empty()){
37 int qsize = q.size();
38
39 while(qsize-- > 0){
40 pair<int, long long> pr = q.front(); q.pop();
41 int start = pr.first;
42 long long currem = pr.second;
43
44 if((total - currem) % p == 0){
45 return (remlen == n) ? -1 : remlen;
46 }
47
48 if(start+remlen < n){
49 q.push({start, currem+nums[start+remlen]});
50 }
51 }
52
53 ++remlen;
54 }
55
56 return -1;
57 }
58};
59
60//hashmap
61//Runtime: 372 ms, faster than 76.44% of C++ online submissions for Make Sum Divisible by P.
62//Memory Usage: 67 MB, less than 66.04% of C++ online submissions for Make Sum Divisible by P.
63//time: O(N), space: O(N)
64class Solution {
65public:
66 int minSubarray(vector<int>& nums, int p) {
67 int n = nums.size();
68
69 int k = accumulate(nums.begin(), nums.end(), 0LL) % p;
70
71 // cout << "need: " << k << endl;
72
73 if(k == 0) return 0;
74
75 //need to use unordered_map, if using vector, it will give TLE!!
76 unordered_map<int, int> lastidx;
77 /*
78 cannot set ans as "INT_MAX",
79 because we should not allow the case s.t.
80 we need to remove the whole array to make the sum%p=k,
81 in this case, ans will be n(remove whole array)
82 */
83 int ans = n;
84 int runsum = 0;
85
86 // lastidx[0] = -1;
87 for(int i = 0; i < n; ++i){
88 runsum = (runsum+nums[i])%p;
89 if(lastidx.count((runsum-k+p)%p)){
90 /*
91 nums[lastidx[?]+1...i] % p = k
92 (runsum-?) % p = k
93 ? = (runsum-k+p) % p
94 */
95 ans = min(ans, i - lastidx[(runsum-k+p)%p]);
96 }
97 /*
98 runsum don't need to subtract anything to become k%p
99 */
100 if(runsum == k){
101 ans = min(ans, i+1);
102 }
103 lastidx[runsum] = i;
104 // cout << "lastidx[" << runsum << "] = " << i << endl;
105 }
106
107 return (ans == n) ? -1 : ans;
108 }
109};
110
111//revise from above, merge the case of sum from beginning into lastidx[0] = -1;
112//Runtime: 368 ms, faster than 82.78% of C++ online submissions for Make Sum Divisible by P.
113//Memory Usage: 66.8 MB, less than 91.49% of C++ online submissions for Make Sum Divisible by P.
114class Solution {
115public:
116 int minSubarray(vector<int>& nums, int p) {
117 int n = nums.size();
118
119 int k = accumulate(nums.begin(), nums.end(), 0LL) % p;
120
121 if(k == 0) return 0;
122
123 unordered_map<int, int> lastidx;
124 int ans = n;
125 int runsum = 0;
126
127 lastidx[0] = -1;
128 for(int i = 0; i < n; ++i){
129 runsum = (runsum+nums[i])%p;
130 if(lastidx.count((runsum-k+p)%p)){
131 ans = min(ans, i - lastidx[(runsum-k+p)%p]);
132 }
133 lastidx[runsum] = i;
134 }
135
136 return (ans == n) ? -1 : ans;
137 }
138};
Cost