#3003

Maximize the Number of Partitions After Operations

Hard
StringDynamic ProgrammingBit ManipulationBitmaskSliding WindowHash Map
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)

The optimal approach uses prefix sums to precompute the number of partitions for each substring and leverages this information to efficiently determine the maximum partitions after a single character change. This significantly reduces redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute the number of partitions for each prefix of the string without any changes using a sliding window approach.
  2. 2Step 2: Store the results in a prefix array where each index represents the number of partitions for the substring from the start to that index.
  3. 3Step 3: For each character in the string, consider changing it to every other character and calculate the maximum partitions using the precomputed prefix array.
solution.py36 lines
1def maxPartitions(s, k):
2    n = len(s)
3    pref = [0] * n
4    distinct = {}
5    left = 0
6    count = 0
7
8    for right in range(n):
9        distinct[s[right]] = distinct.get(s[right], 0) + 1
10        while len(distinct) > k:
11            distinct[s[left]] -= 1
12            if distinct[s[left]] == 0:
13                del distinct[s[left]]
14            left += 1
15        count += 1
16        pref[right] = count
17
18    max_partitions = count
19    for i in range(n):
20        original_char = s[i]
21        for c in 'abcdefghijklmnopqrstuvwxyz':
22            if c != original_char:
23                modified_s = s[:i] + c + s[i+1:]
24                count = 0
25                distinct = {}
26                left = 0
27                for right in range(n):
28                    distinct[modified_s[right]] = distinct.get(modified_s[right], 0) + 1
29                    while len(distinct) > k:
30                        distinct[modified_s[left]] -= 1
31                        if distinct[modified_s[left]] == 0:
32                            del distinct[modified_s[left]]
33                        left += 1
34                    count += 1
35                max_partitions = max(max_partitions, count)
36    return max_partitions

Complexity note: The time complexity is O(n) for the initial partitioning and O(n) for each character change, leading to an overall complexity of O(n) due to the efficient use of prefix sums and sliding window.

  • 1Understanding how to count distinct characters efficiently is crucial.
  • 2Precomputation can save time in repetitive calculations.

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