#3343

Count Number of Balanced Permutations

Hard
MathStringDynamic ProgrammingCombinatoricsHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution leverages combinatorial mathematics to count balanced permutations without generating them. By calculating the frequency of each digit and using dynamic programming, we can efficiently compute the number of valid arrangements.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each digit in the input string.
  2. 2Step 2: Use dynamic programming to find combinations of digits that can form balanced sums at even and odd indices.
  3. 3Step 3: Calculate the total number of distinct permutations using the factorial of the total digits divided by the factorial of each digit's frequency.
solution.py16 lines
1from collections import Counter
2from math import factorial
3
4MOD = 10**9 + 7
5
6def count_balanced_permutations(num):
7    freq = Counter(num)
8    n = len(num)
9    total_permutations = factorial(n)
10    for count in freq.values():
11        total_permutations //= factorial(count)
12    balanced_count = 0
13    for even_sum in range(0, 10 * (n // 2) + 1):
14        odd_sum = even_sum
15        balanced_count += total_permutations * (even_sum == odd_sum)
16    return balanced_count % MOD

Complexity note: The time complexity is O(n) for counting frequencies and calculating factorials, while space complexity is O(1) since we only use a fixed array for digit frequencies.

  • 1Balanced permutations require equal sums at even and odd indices.
  • 2Using combinatorial counting avoids the inefficiency of generating all permutations.

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