#3458

Select K Disjoint Special Substrings

Medium
Hash TableStringDynamic ProgrammingGreedySortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Identify character boundaries to create special substrings efficiently. Use a greedy approach to select the maximum number of disjoint special substrings.

⚙️

Algorithm

3 steps
  1. 1Step 1: Track first and last occurrences of each character in the string.
  2. 2Step 2: Create intervals for each character based on its first and last occurrence.
  3. 3Step 3: Sort intervals and use a greedy approach to count disjoint intervals, ensuring no overlaps.
solution.py14 lines
1def canSelectKDisjointSpecialSubstrings(s, k):
2    first, last = {}, {}
3    for i, c in enumerate(s):
4        if c not in first:
5            first[c] = i
6        last[c] = i
7    intervals = [(first[c], last[c]) for c in first if first[c] != last[c]]
8    intervals.sort(key=lambda x: x[1])
9    count, end = 0, -1
10    for start, finish in intervals:
11        if start > end:
12            count += 1
13            end = finish
14    return count >= k

Complexity note: We only traverse the string a few times, leading to O(n) time complexity.

  • 1Each special substring must have unique characters not found elsewhere.
  • 2Disjoint intervals can be efficiently counted using sorting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.