Optimal Partition of String Problem
#2405
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2405.
Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.
Return the minimum number of substrings in such a partition.
Note that each character should belong to exactly one substring in a partition.
Example 1:
Input: s = "abacaba"
Output: 4
Explanation:
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.
Example 2:
Input: s = "ssssss"
Output: 6
Explanation:
The only valid partition is ("s","s","s","s","s","s").
Constraints:
1 <= s.length <= 10^5sconsists of only English lowercase letters.
Solution
Approach: Greedy
Each piece should be as long as possible, so extend the current piece until a letter repeats, then start a new piece.
Track the letters in the current piece with a bitmask. For each letter, if its bit is already set, count a new piece and clear the mask; then set the letter's bit. Start with one piece.
Complexity: O(n) time and O(1) space.
class Solution:
def partitionString(self, s: str) -> int:
ans, mask = 1, 0
for x in map(lambda c: ord(c) - ord("a"), s):
if mask >> x & 1:
ans += 1
mask = 0
mask |= 1 << x
return ans