LeetCode #3458 — MEDIUM

Select K Disjoint Special Substrings

Move from brute-force thinking to an efficient approach using hash map strategy.

Solve on LeetCode
The Problem

Problem Statement

Given a string s of length n and an integer k, determine whether it is possible to select k disjoint special substrings.

A special substring is a substring where:

  • Any character present inside the substring should not appear outside it in the string.
  • The substring is not the entire string s.

Note that all k substrings must be disjoint, meaning they cannot overlap.

Return true if it is possible to select k such disjoint special substrings; otherwise, return false.

Example 1:

Input: s = "abcdbaefab", k = 2

Output: true

Explanation:

  • We can select two disjoint special substrings: "cd" and "ef".
  • "cd" contains the characters 'c' and 'd', which do not appear elsewhere in s.
  • "ef" contains the characters 'e' and 'f', which do not appear elsewhere in s.

Example 2:

Input: s = "cdefdc", k = 3

Output: false

Explanation:

There can be at most 2 disjoint special substrings: "e" and "f". Since k = 3, the output is false.

Example 3:

Input: s = "abeabe", k = 0

Output: true

Constraints:

  • 2 <= n == s.length <= 5 * 104
  • 0 <= k <= 26
  • s consists only of lowercase English letters.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: Given a string s of length n and an integer k, determine whether it is possible to select k disjoint special substrings. A special substring is a substring where: Any character present inside the substring should not appear outside it in the string. The substring is not the entire string s. Note that all k substrings must be disjoint, meaning they cannot overlap. Return true if it is possible to select k such disjoint special substrings; otherwise, return false.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Hash Map · Dynamic Programming · Greedy

Example 1

"abcdbaefab"
2

Example 2

"cdefdc"
3

Example 3

"abeabe"
0

Related Problems

  • Find Longest Self-Contained Substring (find-longest-self-contained-substring)
Step 02

Core Insight

What unlocks the optimal approach

  • There are at most 26 start points (which are the first occurrence of each letter) and at most 26 end points (which are the last occurrence of each letter) of the substring.
  • Starting from each character, build the smallest special substring interval containing it.
  • Use dynamic programming on the obtained intervals to check if it's possible to pick at least <code>k</code> disjoint intervals.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3458: Select K Disjoint Special Substrings
class Solution {
  public boolean maxSubstringLength(String s, int k) {
    final int n = s.length();
    int[] first = new int[26];
    int[] last = new int[26];
    // dp[i] := the maximum disjoint special substrings for the first i letters
    int[] dp = new int[n + 1];
    List<Character> seenOrder = new ArrayList<>();

    Arrays.fill(first, n);
    Arrays.fill(last, -1);

    for (int i = 0; i < n; ++i) {
      final char c = s.charAt(i);
      final int a = c - 'a';
      if (first[a] == n) {
        first[a] = i;
        seenOrder.add(c);
      }
      last[a] = i;
    }

    for (final char c : seenOrder) {
      final int a = c - 'a';
      for (int j = first[a]; j < last[a]; ++j) {
        final int b = s.charAt(j) - 'a';
        first[a] = Math.min(first[a], first[b]);
        last[a] = Math.max(last[a], last[b]);
      }
    }

    for (int i = 0; i < n; i++) {
      final char c = s.charAt(i);
      final 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] = Math.max(dp[i], 1 + dp[first[a]]);
    }

    return dp[n] >= k;
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Mutating counts without cleanup

Wrong move: Zero-count keys stay in map and break distinct/count constraints.

Usually fails on: Window/map size checks are consistently off by one.

Fix: Delete keys when count reaches zero.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.