Optimal Partition of String - Problem

You are given a string s and need to find the most efficient way to partition it into substrings where every character in each substring appears exactly once.

Think of it as cutting the string into pieces where no piece contains duplicate characters. Your goal is to make the minimum number of cuts possible.

Example: If s = "abcabc", you could partition it as ["abc", "abc"] for 2 substrings, or ["a", "b", "c", "a", "b", "c"] for 6 substrings. The optimal solution uses 2 substrings.

Return the minimum number of substrings needed for such a partition.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "abcabc"
โ€บ Output: 2
๐Ÿ’ก Note: The optimal partition is ["abc", "abc"]. When we reach the second 'a', we must start a new partition since 'a' already exists in the current substring.
example_2.py โ€” No Duplicates
$ Input: s = "abcdef"
โ€บ Output: 1
๐Ÿ’ก Note: All characters are unique, so the entire string forms one partition ["abcdef"].
example_3.py โ€” All Same Characters
$ Input: s = "aaaa"
โ€บ Output: 4
๐Ÿ’ก Note: Every character is a duplicate of the previous, so we need 4 partitions: ["a", "a", "a", "a"].

Constraints

  • 1 โ‰ค s.length โ‰ค 104
  • s consists of only lowercase English letters
  • Each character must belong to exactly one substring

Visualization

Tap to expand
๐Ÿ“š Library Reading SessionsEach session can only have people with unique namesSession 1AliceBobCarolโœ“ All names uniqueSession continues...โŒ Alice arrives again!AliceCannot join Session 1Must start Session 2!Decision Point: Start New SessionSession 2AliceBobCarolFresh start with unique names๐ŸŽฏ Result: 2 sessions needed (greedy approach is optimal!)
Understanding the Visualization
1
Start First Session
Begin with an empty reading room (hash set)
2
Add People
As people arrive, add them to current session if name is unique
3
Handle Duplicates
When someone with duplicate name arrives, start new session
4
Reset Room
Clear the room and add the duplicate person to fresh session
Key Takeaway
๐ŸŽฏ Key Insight: The moment we encounter a duplicate, we must start a new partition - no need to look ahead or try different combinations!
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
38.4K Views
High Frequency
~12 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen