#1520
Maximum Number of Non-Overlapping Substrings
HardHash TableStringGreedySortingHash MapGreedy Algorithm
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution involves using a greedy approach with a two-pass technique. We first determine the last occurrence of each character, then we find the maximum number of non-overlapping substrings by iterating through the string and ensuring we include all occurrences of each character.
⚙️
Algorithm
3 steps- 1Step 1: Create a map to store the last occurrence index of each character.
- 2Step 2: Iterate through the string to determine the end index for each substring based on the last occurrence of characters.
- 3Step 3: Use a greedy approach to select non-overlapping substrings by checking if the current substring can be added without overlap.
solution.py12 lines
1def maxNonOverlappingSubstrings(s):
2 last = {c: i for i, c in enumerate(s)}
3 result = []
4 end = -1
5 start = 0
6 while start < len(s):
7 current_end = last[s[start]]
8 for i in range(start, current_end + 1):
9 current_end = max(current_end, last[s[i]])
10 result.append(s[start:current_end + 1])
11 start = current_end + 1
12 return resultℹ
Complexity note: The time complexity is O(n) because we make a single pass to determine last occurrences and another pass to find substrings. The space complexity is O(n) due to the storage of last occurrences in a map.
- 1Understanding character occurrences is crucial for substring selection.
- 2Greedy algorithms can effectively maximize non-overlapping selections.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.