← Home

1520. Maximum Number of Non-Overlapping Substrings

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
152

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 1520. Maximum Number of Non-Overlapping Substrings, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: two pointers, greedy.

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

  • Greedy
  • https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/discuss/743223/C%2B%2BJava-Greedy-O(n)
  • time: O(N), because the inner loop will be executed at most 26 times, this is ensured by "if(l[s[i]-'a'] == i)"
  • space: O(1)

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 checkSubstr, maxNumOfSubstrings, l.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Substring checks are convenient but not free, so they are part of the real complexity story.
  • 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), because the inner loop will be executed at most 26 times, this is ensured by "if(l[s[i]-'a'] == i)"
  • Space: O(1)

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Greedy
02//https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/discuss/743223/C%2B%2BJava-Greedy-O(n)
03//Runtime: 156 ms, faster than 98.13% of C++ online submissions for Maximum Number of Non-Overlapping Substrings.
04//Memory Usage: 20 MB, less than 100.00% of C++ online submissions for Maximum Number of Non-Overlapping Substrings.
05//time: O(N), because the inner loop will be executed at most 26 times, this is ensured by "if(l[s[i]-'a'] == i)"
06//space: O(1)
07class Solution {
08public:
09    int checkSubstr(string& s, int i, vector<int>& l, vector<int>& r){
10        //check: all other chars in [l[c], r[c]] don't start before i
11        //also find the new "right" to include all occurences of those chars
12        //this logic will ensure that we find the valid substring with the smallest right edge
13        int right = r[s[i]-'a'];
14        
15        for(int j = i; j <= right; ++j){
16            if(l[s[j]-'a'] < i){
17                return -1;
18            }
19            right = max(right, r[s[j]-'a']);
20        }
21        
22        return right;
23    };
24    
25    vector<string> maxNumOfSubstrings(string s) {
26        vector<int> l(26, INT_MAX), r(26, INT_MIN);
27        int n = s.size();
28        
29        for(int i = 0; i < n; ++i){
30            l[s[i]-'a'] = min(l[s[i]-'a'], i);
31            r[s[i]-'a'] = max(r[s[i]-'a'], i);
32        }
33        
34        vector<string> ans;
35        int right = INT_MAX;
36        for(int i = 0; i < n; ++i){
37            if(l[s[i]-'a'] == i){
38                /*
39                current char is the start of its kind of char, 
40                it's candidate valid substring
41                */
42                
43                int newright = checkSubstr(s, i, l, r);
44                if(newright != -1){
45                    if(i > right || ans.empty()){
46                        /*
47                        "right" is the right boundary of previous valid substring
48                        if "i > right", then current substring doesn't overlap
49                        with previous substring,
50                        so the previous valid substring doesn't need to be
51                        overwritten
52                        */
53                        ans.push_back("");
54                    }
55                    right = newright;
56                    //overwrite the previous valid substring
57                    /*
58                    greedy:
59                    
60                    If we find a valid substring, 
61                    and then another valid substring 
62                    within the first substring - 
63                    we can ignore the larger substring.
64                    
65                    E.g. if we find "abccba", and then "bccb", 
66                    and then "cc", we only care about "cc". 
67                    This can be easily proven by a contradition.
68                    
69                    When two valid substring overlap,
70                    one substring must contain another?
71                    */
72                    ans.back() = s.substr(i, right-i+1);
73                }
74            }
75        }
76        
77        return ans;
78    }
79};

Cost

Complexity

Time
O(N), because the inner loop will be executed at most 26 times, this is ensured by "if(l[s[i]-'a'] == i)"
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(1)
Auxiliary state plus the answer structure where the problem requires one.