- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 74 lines of Python from the credited upstream file maximum-number-of-non-overlapping-substrings.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution(object):5 def maxNumOfSubstrings(self, s):6 """7 :type s: str8 :rtype: List[str]9 """10 def find_right_from_left(s, first, last, left):11 right, i = last[ord(s[left])-ord('a')], left12 while i <= right:13 if first[ord(s[i])-ord('a')] < left:14 return -115 right = max(right, last[ord(s[i])-ord('a')])16 i += 117 return right18 19 first, last = [float("inf")]*26, [float("-inf")]*2620 for i, c in enumerate(s):21 first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)22 last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)23 result = [""]24 right = float("inf")25 for left, c in enumerate(s):26 if left != first[ord(c)-ord('a')]:27 continue28 new_right = find_right_from_left(s, first, last, left)29 if new_right == -1:30 continue31 if left > right:32 result.append("")33 right = new_right34 result[-1] = s[left:right+1]35 return result36 37 383940class Solution2(object):41 def maxNumOfSubstrings(self, s):42 """43 :type s: str44 :rtype: List[str]45 """46 def find_right_from_left(s, first, last, left):47 right, i = last[ord(s[left])-ord('a')], left48 while i <= right:49 if first[ord(s[i])-ord('a')] < left:50 return -151 right = max(right, last[ord(s[i])-ord('a')])52 i += 153 return right54 55 first, last = [float("inf")]*26, [float("-inf")]*2656 for i, c in enumerate(s):57 first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)58 last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)59 intervals = []60 for c in xrange(len(first)):61 if first[c] == float("inf"):62 continue63 left, right = first[c], find_right_from_left(s, first, last, first[c])64 if right != -1:65 intervals.append((right, left))66 intervals.sort() 67 result, prev = [], -168 for right, left in intervals:69 if left <= prev:70 continue71 result.append(s[left:right+1])72 prev = right73 return result74