1. Recursive Partitioning Verification
Intuition
Recursively attempt every valid cut point where characters in the prefix do not occur in the remainder of the string.
Algorithm
- Step 1: Define recursive solve(idx).
- Step 2: If idx == s.length(), return empty partition list.
- Step 3: Scan forward to find the smallest j >= idx such that characters in s[idx..j] do not appear in s[j+1..end].
- Step 4: Append (j - idx + 1) to result and recurse on solve(j + 1).
- Step 5: Return partitions.
Enumerate Cut Boundaries & Validate Disjoint Sets
2 of 2 questions left todayCharacters 'a' and 'b' cross the boundary into the suffix
Characters a and b cross the boundary into the suffix. The cut must be extended.
#include <iostream>#include <vector>#include <string>#include <unordered_set> using namespace std; class Solution {public: vector<int> partitionLabels(string s) { vector<int> ans; int n = s.length(); int i = 0; while (i < n) { unordered_set<char> seen; int j = i; seen.insert(s[i]); for (int k = i; k <= j; ++k) { seen.insert(s[k]); // Extend j to the last occurrence of any seen character for (int m = n - 1; m > j; --m) { if (s[m] == s[k]) { j = m; break; } } } ans.push_back(j - i + 1); i = j + 1; } return ans; }}; int main() { Solution sol; string s = "ababcbacadefegdehijhklij"; vector<int> res = sol.partitionLabels(s); cout << "Partition Sizes: "; for (int len : res) cout << len << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N) - Space complexity:
O(N)