This is one of those problems where the clean idea matters more than the amount of code. For 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum, the solution in this repository is mainly a dynamic programming 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: dynamic programming, sliding window, prefix sums.
The notes already sitting in the source point us in the right direction:
- TLE
- 53 / 57 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 minSumOfLengths, prefix, suffix.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- 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:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- 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
01//TLE
02//53 / 57 test cases passed.
03class Solution {
04public:
05 int minSumOfLengths(vector<int>& arr, int target) {
06 int n = arr.size();
07
08 vector<vector<int>> v;
09 // deque<vector<int>> deq;
10
11// for(int i = 0; i < n; i++){
12// if(arr[i] == target){
13// v.push_back({i, i});
14// // deq.push_back({i, i});
15// // cout << i << ", " << i << endl;
16// }else if(arr[i] < target){
17// int remain = target - arr[i];
18// int j;
19// for(j = i+1; j < n && remain > 0; remain -= arr[j++]){
20
21// }
22// if(remain == 0){
23// j--;
24// v.push_back({i, j});
25// // cout << i << ", " << j << endl;
26// }
27// }
28// }
29
30 int windowSum = 0, slow = 0, fast = 0;
31 for(;fast < n;fast++){
32 while(fast < n && windowSum < target){
33 windowSum += arr[fast++];
34 }
35 fast--;
36 if(windowSum == target){
37 v.push_back({slow, fast});
38 // cout << slow << ", " << fast << ", " << windowSum << endl;
39 windowSum -= arr[slow++];
40 }else{
41 while(windowSum > target){
42 cout << slow << ", " << fast << ", " << windowSum << endl;
43 windowSum -= arr[slow++];
44 // cout << slow << ", " << fast << ", " << windowSum << endl;
45 if(windowSum == target){
46 v.push_back({slow, fast});
47 }
48 }
49 // windowSum -= arr[slow];
50 }
51 // cout << slow << ", " << fast << ", " << windowSum << endl;
52 // windowSum -= arr[slow];
53 // slow++;
54 }
55
56 // cout << endl;
57
58 if(v.size() < 2) return -1;
59
60 sort(v.begin(), v.end(), [](const vector<int>& a, const vector<int>& b){
61 return a[1]-a[0] < b[1]-b[0];
62 });
63
64 int start = v[0][0], end = v[0][1];
65
66 for(int i = 1; i < v.size(); i++){
67 if(v[i][1] < start || v[i][0] > end){
68 return (end-start+1) + (v[i][1]-v[i][0]+1);
69 }
70 }
71
72 return -1;
73 }
74};
75
76//DP
77/*
78Hint 1: Let's create two arrays prefix and suffix where
79prefix[i] is the minimum length of sub-array ends before i and has sum = k,
80suffix[i] is the minimum length of sub-array starting at or after i and has sum = k.
81
82Hint 2: The answer we are searching for is min(prefix[i] + suffix[i])
83for all values of i from 0 to n-1 where n == arr.length.
84
85Hint 3: If you are still stuck with how to build prefix and suffix,
86you can store for each index i the length of the sub-array starts at i
87and has sum = k or infinity otherwise,
88and you can use it to build both prefix and suffix.
89*/
90//Runtime: 304 ms, faster than 80.00% of C++ online submissions for Find Two Non-overlapping Sub-arrays Each With Target Sum.
91//Memory Usage: 77.1 MB, less than 40.00% of C++ online submissions for Find Two Non-overlapping Sub-arrays Each With Target Sum.
92class Solution {
93public:
94 int minSumOfLengths(vector<int>& arr, int target) {
95 int n = arr.size();
96 /*
97 1 <= arr.length <= 10^5,
98 so "ans = min(prefix[i] + suffix[i])" 's max possible value is
99 1e5+1e5,
100 here we set MAX as 2e5+1,
101 this is the value just above the max possible value
102 */
103 int MAX = 2e5+1;
104 //the minimum length of subarray ends "before" i having sum = target
105 vector<int> prefix(n, MAX);
106 //the minimum length of subarray starts "at" or "after" i having sum = target
107 vector<int> suffix(n, MAX);
108
109 int slow = 0, fast = 0;
110 //the window is [slow, fast]
111 int windowSum = 0;
112 while(fast < n){
113 windowSum += arr[fast];
114
115 while(slow <= fast && windowSum > target){
116 windowSum -= arr[slow++];
117 }
118
119 if(windowSum == target){
120 if(fast+1 < n){
121 prefix[fast+1] = fast-slow+1;
122 }
123 }
124
125 fast++;
126 }
127
128 slow = n-1;
129 fast = n-1;
130 windowSum = 0;
131 //the window is [fast, slow]
132 while(fast >= 0){
133 windowSum += arr[fast];
134
135 while(slow >= fast && windowSum > target){
136 windowSum -= arr[slow--];
137 }
138
139 if(windowSum == target){
140 suffix[fast] = slow-fast+1;
141 }
142
143 fast--;
144 }
145
146 for(int i = 1; i < n; i++){
147 prefix[i] = min(prefix[i], prefix[i-1]);
148 }
149
150 for(int i = n-2; i >= 0; i--){
151 suffix[i] = min(suffix[i], suffix[i+1]);
152 }
153
154// for(int e : prefix){
155// cout << e << " ";
156// }
157// cout << endl;
158
159// for(int e : suffix){
160// cout << e << " ";
161// }
162// cout << endl;
163
164 int ans = INT_MAX;
165
166 for(int i = 0; i < n; i++){
167 /*
168 since prefix[i] ends at j <= i-1,
169 and suffix[i] starts at j >= i,
170 so the two subarrays won't overlap!
171 */
172 ans = min(ans, prefix[i] + suffix[i]);
173 }
174
175 return (ans >= MAX) ? -1 : ans;
176 }
177};
Cost