Problem solution · C++

Select K Disjoint Special Substrings

Select K Disjoint Special Substrings: a C++ solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Disjoint set union
Source
walkccc LeetCode Solutions
Length
42 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For Select K Disjoint Special Substrings, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. Answer connectivity or component queries from the compressed representatives.

Code notes

  • 42 lines of C++ from the credited upstream file 3458.cpp.
  • The implementation visibly relies on sequence storage, cached states.
  • 4 loop blocks detected.

Complexity

Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeSelect K Disjoint Special Substrings · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  bool maxSubstringLength(string s, int k) {    const int n = s.length();    vector<int> first(26, n);    vector<int> last(26, -1);    vector<char> seenOrder;    // dp[i] := the maximum disjoint special substrings for the first i letters    vector<int> dp(n + 1);     for (int i = 0; i < n; ++i) {      const char c = s[i];      const int a = c - 'a';      if (first[a] == n) {        first[a] = i;        seenOrder.push_back(c);      }      last[a] = i;    }     for (const char c : seenOrder) {      const int a = c - 'a';      for (int j = first[a]; j < last[a]; ++j) {        const int b = s[j] - 'a';        first[a] = min(first[a], first[b]);        last[a] = max(last[a], last[b]);      }    }     for (int i = 0; i < n; ++i) {      const char c = s[i];      const int a = c - 'a';      if (last[a] != i || (first[a] == 0 && i == n - 1))        dp[i + 1] = dp[i];      else  // Start a new special substring.        dp[i + 1] = max(dp[i], 1 + dp[first[a]]);    }     return dp[n] >= k;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗