- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 44 lines of Java from the credited upstream file 3458.java.
- 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.
Use this to learn the idea, then write your own version.
1class Solution {2 public boolean maxSubstringLength(String s, int k) {3 final int n = s.length();4 int[] first = new int[26];5 int[] last = new int[26];6 7 int[] dp = new int[n + 1];8 List<Character> seenOrder = new ArrayList<>();9 10 Arrays.fill(first, n);11 Arrays.fill(last, -1);12 13 for (int i = 0; i < n; ++i) {14 final char c = s.charAt(i);15 final int a = c - 'a';16 if (first[a] == n) {17 first[a] = i;18 seenOrder.add(c);19 }20 last[a] = i;21 }22 23 for (final char c : seenOrder) {24 final int a = c - 'a';25 for (int j = first[a]; j < last[a]; ++j) {26 final int b = s.charAt(j) - 'a';27 first[a] = Math.min(first[a], first[b]);28 last[a] = Math.max(last[a], last[b]);29 }30 }31 32 for (int i = 0; i < n; i++) {33 final char c = s.charAt(i);34 final int a = c - 'a';35 if (last[a] != i || (first[a] == 0 && i == n - 1))36 dp[i + 1] = dp[i];37 else 38 dp[i + 1] = Math.max(dp[i], 1 + dp[first[a]]);39 }40 41 return dp[n] >= k;42 }43}44