#3144

Minimum Substring Partition of Equal Character Frequency

Medium
Hash TableStringDynamic ProgrammingCountingHash MapDynamic Programming
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 solution uses dynamic programming to efficiently calculate the minimum number of partitions by leveraging previously computed results. It checks character frequencies in a single pass.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a frequency array to count occurrences of each character.
  2. 2Step 2: Use dynamic programming to store the minimum partitions required for each prefix of the string.
  3. 3Step 3: For each character, update the frequency array and check if the current substring is balanced.
  4. 4Step 4: Update the minimum partitions based on valid partitions found.
solution.py17 lines
1def min_partitions(s):
2    from collections import defaultdict
3    n = len(s)
4    dp = [float('inf')] * n
5    freq = defaultdict(int)
6    for i in range(n):
7        freq[s[i]] += 1
8        if len(set(freq.values())) == 1:
9            dp[i] = 1
10        else:
11            for j in range(i):
12                if len(set(freq.values())) == 1:
13                    dp[i] = min(dp[i], dp[j] + 1)
14        freq[s[i]] -= 1
15        if freq[s[i]] == 0:
16            del freq[s[i]]
17    return dp[-1]

Complexity note: The time complexity is O(n) because we make a single pass through the string, updating frequencies and checking partitions efficiently.

  • 1A balanced substring has equal frequency of all characters.
  • 2Dynamic programming can optimize the solution by storing results of subproblems.

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