2405. Optimal Partition of String LeetCode Solution
In this guide, you will get 2405. Optimal Partition of String LeetCode Solution with the best time and space complexity. The solution to Optimal Partition of String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Optimal Partition of String solution in C++
- Optimal Partition of String solution in Java
- Optimal Partition of String solution in Python
- Additional Resources

Problem Statement of Optimal Partition of String
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 <= 105
s consists of only English lowercase letters.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
2405. Optimal Partition of String LeetCode Solution in C++
class Solution {
public:
int partitionString(string s) {
int ans = 1;
int used = 0;
for (const char c : s) {
const int i = c - 'a';
if (used >> i & 1) {
used = 1 << i;
++ans;
} else {
used |= 1 << i;
}
}
return ans;
}
};
/* code provided by PROGIEZ */
2405. Optimal Partition of String LeetCode Solution in Java
class Solution {
public int partitionString(String s) {
int ans = 1;
int used = 0;
for (final char c : s.toCharArray()) {
final int i = c - 'a';
if ((used >> i & 1) == 1) {
used = 1 << i;
++ans;
} else {
used |= 1 << i;
}
}
return ans;
}
}
// code provided by PROGIEZ
2405. Optimal Partition of String LeetCode Solution in Python
class Solution:
def partitionString(self, s: str) -> int:
ans = 1
used = 0
for c in s:
i = ord(c) - ord('a')
if used >> i & 1:
used = 1 << i
ans += 1
else:
used |= 1 << i
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.