Maximum Substrings With Distinct Start Problem
Description
LeetCode Problem 3760.
You are given a string s consisting of lowercase English letters.
Return an integer denoting the maximum number of substrings you can split s into such that each substring starts with a distinct character (i.e., no two substrings start with the same character).
Example 1:
Input: s = "abab"
Output: 2
Explanation:
- Split "abab" into "a" and "bab".
- Each substring starts with a distinct character i.e 'a' and 'b'. Thus, the answer is 2.
Example 2:
Input: s = "abcd"
Output: 4
Explanation:
- Split "abcd" into "a", "b", "c", and "d".
- Each substring starts with a distinct character. Thus, the answer is 4.
Example 3:
Input: s = "aaaa"
Output: 1
Explanation:
- All characters in "aaaa" are 'a'.
- Only one substring can start with 'a'. Thus, the answer is 1.
Constraints:
1 <= s.length <= 10^5sconsists of lowercase English letters.
Solution
Approach: Count Distinct Letters
Each substring must start with a letter that no other substring starts with, so the number of substrings can never exceed the number of distinct letters in s. That bound is reachable: cut the string right before the first occurrence of every letter (the first substring starts at the first character anyway). Each piece then starts with a different letter, one piece per distinct letter.
So the answer is simply the number of distinct letters in s, which we find by marking the 26 letters as we scan.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxDistinct(self, s: str) -> int:
return len(set(s))