Optimal Partition of String - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcabc"
Output: 2
💡 Note: Split into "abc" and "abc". Each substring has unique characters. We cannot do better than 2 partitions because 'a' appears again at position 3.
Example 2 — All Unique
$ Input: s = "abcd"
Output: 1
💡 Note: All characters are unique, so we only need 1 partition containing the entire string.
Example 3 — All Same
$ Input: s = "aaaa"
Output: 4
💡 Note: Every character is the same, so each must be in its own partition: "a", "a", "a", "a".

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of only English lowercase letters

Visualization

Tap to expand
Optimal Partition of StringInput: "abcabc"abcabcSplit here('a' repeats)Partitions:"abc""abc"All uniqueAll uniqueOutput: 2Minimum number of partitions with unique characters
Understanding the Visualization
1
Input
String that may contain duplicate characters
2
Process
Partition at duplicate character boundaries
3
Output
Minimum number of partitions needed
Key Takeaway
🎯 Key Insight: Use greedy approach - partition only when necessary (at duplicate characters)
Asked in
Amazon 35 Google 25 Microsoft 20
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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