Partition String - Problem

Given a string s, partition it into unique segments according to the following procedure:

1. Start building a segment beginning at index 0

2. Continue extending the current segment character by character until the current segment has not been seen before

3. Once the segment is unique, add it to your list of segments, mark it as seen, and begin a new segment from the next index

4. Repeat until you reach the end of s

Return an array of strings segments, where segments[i] is the ith segment created.

Input & Output

Example 1 — Basic Partitioning
$ Input: s = "abcabc"
Output: ["a","b","c","ab","c"]
💡 Note: Start with "a" (unique), then "b" (unique), then "c" (unique). Next, "a" is seen so extend to "ab" (unique). Finally "c" is seen but we're at end, so add "c".
Example 2 — Repeated Characters
$ Input: s = "ababccc"
Output: ["a","b","ab","c","cc"]
💡 Note: "a" is unique, "b" is unique, "a" is seen so extend to "ab" (unique), "c" is unique, "c" is seen so extend to "cc" (unique).
Example 3 — Single Character
$ Input: s = "a"
Output: ["a"]
💡 Note: Only one character, so the entire string "a" forms one unique segment.

Constraints

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

Visualization

Tap to expand
Partition String - Hash Set Optimization INPUT String s = "abcabc" a 0 b 1 c 2 a 3 b 4 c 5 Hash Set (seen segments) { } Initially empty O(1) lookup time Input Parameters s = "abcabc" length = 6 ALGORITHM STEPS 1 Initialize seen={}, result=[], i=0 2 Build Segment Extend char by char 3 Check Unique If not in seen set 4 Add and Continue Add to result, mark seen Iteration Trace: "a" not in seen --> add "a" "b" not in seen --> add "b" "c" not in seen --> add "c" "a" in seen, try "ab" "ab" not in seen --> add "c" in seen --> end of s FINAL RESULT Partitioned Segments: "a" "b" "c" "ab" "c" Final Hash Set: {"a","b","c","ab"} 4 unique segments stored Output Array ["a","b","c","ab","c"] OK - Valid Partition 5 segments, all unique when added Key Insight: The Hash Set enables O(1) lookup to check if a segment was seen before. We greedily take the shortest unique segment at each position. Note: "c" appears twice in output because "c" was already in the set when we reached index 5, but we had no more characters to extend it. Time: O(n^2), Space: O(n) TutorialsPoint - Partition String | Hash Set Optimization Approach
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 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