Sponsored
Sponsored
This approach uses a greedy method to partition the string. We traverse the string while keeping track of seen characters in a HashSet. When a repeating character is encountered, we start a new substring. This way, we ensure that each substring contains unique characters.
Time Complexity: O(n), where n is the length of the string, as we traverse each character once.
Space Complexity: O(1), since the size of the HashSet or boolean array is constant (fixed alphabet size).
1#include <iostream>
2#include <unordered_set>
3using namespace std;
4
5int minSubstrings(string s) {
6 unordered_set<char> seen;
7 int count = 0;
8
9 for (char c : s) {
10 if (seen.count(c)) {
11 count++;
12 seen.clear(); // Reset
13 }
14 seen.insert(c);
15 }
16 return count + 1;
17}
18
19int main() {
20 string s = "abacaba";
21 cout << minSubstrings(s) << endl; // Output: 4
22 return 0;
23}
A HashSet
helps track unique characters in the current substring. When a duplicate character is found, the set is cleared, and a new count begins.
With the two-pointer technique, one pointer iterates over the string while another pointer marks the start of a current substring. If a repeat character is found, we adjust the start pointer to ensure all characters between the start and end pointers remain unique.
Time Complexity: O(n), bounds on string traversal.
Space Complexity: O(1), with 26 possible character slots.
1
public class Solution {
public int MinSubstrings(string s) {
int[] lastSeen = new int[26];
for (int i = 0; i < 26; ++i) lastSeen[i] = -1;
int start = 0, count = 1;
for (int i = 0; i < s.Length; ++i) {
if (lastSeen[s[i] - 'a'] >= start) {
count++;
start = i;
}
lastSeen[s[i] - 'a'] = i;
}
return count;
}
public static void Main(string[] args) {
Solution sol = new Solution();
Console.WriteLine(sol.MinSubstrings("abacaba")); // Output: 4
}
}
This method utilizes an integer array lastSeen
to track character indices for optimizing substring formations.