#2405
Optimal Partition of String
MediumHash TableStringGreedyHash 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)
The optimal solution uses a greedy approach where we iterate through the string and keep track of characters we've seen in the current substring. When we encounter a duplicate character, we start a new substring.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a set to keep track of characters in the current substring.
- 2Step 2: Initialize a counter for the number of substrings.
- 3Step 3: Iterate through each character in the string. If the character is already in the set, increment the substring counter and clear the set.
- 4Step 4: Add the character to the set.
- 5Step 5: Return the total count of substrings.
solution.py12 lines
1# Full working Python code
2
3def min_partitions(s):
4 seen = set()
5 count = 1
6 for char in s:
7 if char in seen:
8 count += 1
9 seen.clear()
10 seen.add(char)
11 return count
12ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the string, and the space complexity is O(n) due to the set used to track characters.
- 1The problem can be solved efficiently by using a greedy approach that focuses on character uniqueness.
- 2Tracking characters with a set allows for quick checks and updates, optimizing performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.