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 String INPUT String s = "abcabc" a 0 b 1 c 2 a 3 b 4 c 5 Goal: Partition into substrings where each character appears at most once s = "abcabc" ALGORITHM STEPS 1 Initialize Set seen={}, count=1 2 Iterate chars Process: a,b,c,a,b,c 3 Check duplicate If in set: new partition 4 Return count Total partitions needed Trace: i=0: 'a' new, seen={a} i=1: 'b' new, seen={a,b} i=2: 'c' new, seen={a,b,c} i=3: 'a' DUP! count=2 reset seen={a} i=4,5: b,c added FINAL RESULT Partition 1: a b c "abc" - all unique Partition 2: a b c "abc" - all unique Output: 2 OK - Minimum partitions! Key Insight: Greedy approach: Extend current partition as long as possible until a duplicate is found. Use a HashSet to track characters in the current partition. When duplicate detected, start a new partition and increment count. Time: O(n), Space: O(26) = O(1) for lowercase. TutorialsPoint - Optimal Partition of String | Greedy Approach
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