Partition String - Problem

You have a string s that you need to partition into unique segments using a greedy approach. The goal is to create the shortest possible segments while ensuring no two segments are identical.

Algorithm:

  1. Start at index 0 and build a segment character by character
  2. Keep extending the current segment until it becomes unique (not seen before)
  3. Once unique, add it to your result and mark it as "seen"
  4. Start a new segment from the next index
  5. Repeat until the entire string is processed

Example: For string "abcabc", we get segments ["a", "b", "c", "ab", "c"] because when we reach the second 'a', we need "ab" to make it unique since "a" was already seen.

Input & Output

example_1.py — Basic Case
$ Input: s = "abcabc"
Output: ["a", "b", "c", "ab", "c"]
💡 Note: Start with 'a' (unique) → 'b' (unique) → 'c' (unique) → second 'a' is seen, so extend to 'ab' (unique) → final 'c' is seen but we're at the end, so it becomes a separate segment
example_2.py — Repeated Pattern
$ Input: s = "aaaa"
Output: ["a", "aa", "aaa"]
💡 Note: First 'a' is unique. Second 'a' is seen, but 'aa' is unique. Third 'a' is seen, 'aa' is seen, but 'aaa' is unique. Fourth 'a' continues the pattern.
example_3.py — All Unique Characters
$ Input: s = "abcdef"
Output: ["a", "b", "c", "d", "e", "f"]
💡 Note: Each character is unique on its own, so each forms its own segment - this is the optimal greedy solution.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters only
  • The algorithm must use a greedy approach - always choose the shortest unique segment

Visualization

Tap to expand
Partition String - Greedy Approach INPUT String s = "abcabc" a 0 b 1 c 2 a 3 b 4 c 5 Processing Flow: "a" -- unique? YES "b" -- unique? YES "c" -- unique? YES "a" -- unique? NO "ab" -- unique? YES ALGORITHM STEPS 1 Initialize Start at index 0, empty seen set 2 Build Segment Add chars until segment unique 3 Mark as Seen Add unique segment to result 4 Repeat Continue until string ends Seen Set After Processing: "a" "b" "c" "ab" Note: Second "c" is unique (not in set yet) GREEDY: Shortest unique first! FINAL RESULT Partition segments: ["a", "b", "c", "ab", "c"] Segment Breakdown: a b c ab c Total: 5 segments OK - Complete! All segments unique String fully partitioned Key Insight: The greedy approach ensures the SHORTEST possible unique segments by extending only when necessary. When a character sequence already exists in seen set, we keep adding characters until we get a new unique segment. Time Complexity: O(n^2) | Space Complexity: O(n) for storing seen segments TutorialsPoint - Partition String | Greedy Approach
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
24.5K Views
Medium Frequency
~12 min Avg. Time
892 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