#3760
Maximum Substrings With Distinct Start
MediumHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n²) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can traverse the string while keeping track of the last occurrence of each character. This allows us to split the string efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array to track the last index of each character.
- 2Step 2: Traverse the string and determine the end of each substring based on the last occurrence of characters.
- 3Step 3: Count the number of distinct substrings by checking the end indices.
solution.py11 lines
1def maxDistinctSubstrings(s):
2 last_index = {c: -1 for c in set(s)}
3 end = 0
4 count = 0
5 for i, c in enumerate(s):
6 end = max(end, last_index[c])
7 if i == end:
8 count += 1
9 end = i + 1
10 last_index[c] = i
11 return countℹ
Complexity note: We traverse the string once, maintaining a map of last indices, leading to O(n) time and space complexity.
- 1Each distinct starting character can form a substring.
- 2The last occurrence of characters determines valid splits.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.