#3597
Partition String
MediumHash TableStringTrieSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach uses a single pass through the string while maintaining a set of seen segments, ensuring each segment is built only once and checked for uniqueness efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty list for segments and a set for seen segments.
- 2Step 2: Use a loop to build segments character by character, checking against the seen set.
- 3Step 3: If a segment is unique, add it to the list and update the seen set.
solution.py11 lines
1def partition_string(s):
2 segments, seen = [], set()
3 segment = ''
4 for char in s:
5 segment += char
6 if segment in seen:
7 segments.append(segment[:-1])
8 seen.add(segment[:-1])
9 segment = char
10 segments.append(segment)
11 return segmentsℹ
Complexity note: Each character is processed once, leading to O(n). The space complexity accounts for the segments and seen set.
- 1Segments must be unique, so tracking seen segments is crucial.
- 2Building segments dynamically helps avoid unnecessary checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.