Problem solution · C++

Maximum Number of Non-Overlapping Substrings

Maximum Number of Non-Overlapping Substrings: a C++ solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
45 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Maximum Number of Non-Overlapping Substrings, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 45 lines of C++ from the credited upstream file 1520.cpp.
  • The implementation visibly relies on sequence storage.
  • 3 loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum Number of Non-Overlapping Substrings · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  vector<string> maxNumOfSubstrings(string s) {    const int n = s.length();    vector<string> ans;    // leftmost[i] := the leftmost index of ('a' + i)    vector<int> leftmost(26, n);    // rightmost[i] := the rightmost index of ('a' + i)    vector<int> rightmost(26, -1);     for (int i = 0; i < n; ++i) {      leftmost[s[i] - 'a'] = min(leftmost[s[i] - 'a'], i);      rightmost[s[i] - 'a'] = i;    }     auto getNewRight = [&](int i) {      int right = rightmost[s[i] - 'a'];      for (int j = i; j <= right; ++j) {        if (leftmost[s[j] - 'a'] < i)  // Find a letter's leftmost index < i.          return -1;        // Expand the right dynamically.        right = max(right, rightmost[s[j] - 'a']);      }      return right;    };     int right = -1;  // the rightmost index of the last substring    for (int i = 0; i < n; ++i) {      // the current index is the first appearance      if (i == leftmost[s[i] - 'a']) {        const int newRight = getNewRight(i);        if (newRight == -1)          continue;  // Find a letter's leftmost index < i.        if (i <= right && !ans.empty())          ans.back() = s.substr(i, newRight - i + 1);        else          ans.push_back(s.substr(i, newRight - i + 1));        right = newRight;      }    }     return ans;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗