Optimal Partition of String

medium greedy string hash set

Problem

You are given a string s of lowercase English letters. Split it into one or more non-overlapping substrings that together cover the whole string, with the rule that no letter may appear twice inside the same substring. Return the minimum number of substrings such a split can have.

Inputs = "abacaba"
Output4
One optimal split is "ab" | "ac" | "ab" | "a" — every piece has all-distinct letters, and no valid split uses fewer than 4 pieces.

def partition_string(s):
    seen = set()
    parts = 1
    for ch in s:
        if ch in seen:
            parts += 1        # cut: start a new piece
            seen = set()
        seen.add(ch)          # current char joins the piece
    return parts
function partitionString(s) {
  let seen = new Set();
  let parts = 1;
  for (const ch of s) {
    if (seen.has(ch)) {
      parts++;             // cut: start a new piece
      seen = new Set();
    }
    seen.add(ch);          // current char joins the piece
  }
  return parts;
}
int partitionString(String s) {
    Set<Character> seen = new HashSet<>();
    int parts = 1;
    for (char ch : s.toCharArray()) {
        if (seen.contains(ch)) {
            parts++;           // cut: start a new piece
            seen.clear();
        }
        seen.add(ch);          // current char joins the piece
    }
    return parts;
}
int partitionString(string s) {
    unordered_set<char> seen;
    int parts = 1;
    for (char ch : s) {
        if (seen.count(ch)) {
            parts++;           // cut: start a new piece
            seen.clear();
        }
        seen.insert(ch);       // current char joins the piece
    }
    return parts;
}
Time: O(n) Space: O(1)