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.

Input: s = "abacaba"
Output: 4
Explanation: Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
So, we can return 4.
Input: s = "ssssss"
Output: 6
Explanation: The only valid partition is ("s","s","s","s","s","s").
Constraints:

Contents

In this approach, we will use a HashSet to uniqueness of a substring and when a repeated character is found increment the count of unique substrings.

Implementation steps:
import java.util.HashSet; public class OptimalPartitionOfString { static int partitionString(String s) { HashSet<Character> set = new HashSet<>(); int result = 1; for(char c : s.toCharArray()) { if(set.contains(c)) { result++; set.clear(); } set.add(c); } return result; } public static void main(String[] args) { System.out.println(partitionString("abacaba")); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of input string s
Space complexity: O(1), though we are using a HashSet to store the characters, at most it will have 26 characters at any given time.

Above implementations source code can be found at GitHub link for Java code