Count Number of Balanced Permutations Problem
Description
LeetCode Problem 3343.
You are given a string num. A string of digits is called balanced if the sum of the digits at even indices is equal to the sum of the digits at odd indices.
Return the number of distinct permutations of num that are balanced.
Since the answer may be very large, return it modulo 10^9 + 7.
A permutation is a rearrangement of all the characters of a string.
Example 1:
Input: num = "123"
Output: 2
Explanation:
- The distinct permutations of num are "123", "132", "213", "231", "312" and "321".
- Among them, "132" and "231" are balanced. Thus, the answer is 2.
Example 2:
Input: num = "112"
Output: 1
Explanation:
- The distinct permutations of num are "112", "121", and "211".
- Only "121" is balanced. Thus, the answer is 1.
Example 3:
Input: num = "12345"
Output: 0
Explanation:
- None of the permutations of num are balanced, so the answer is 0.
Constraints:
2 <= num.length <= 80numconsists of digits'0'to'9'only.
Solution
Approach: Memoized search with binomial coefficients
A permutation is balanced when the digits at even positions and at odd positions have the same sum, so the total sum s must be even and each side must sum to s / 2. Count the digits cnt[d].
Decide digit by digit how many copies go to the even positions (n / 2 of them, rounded up) and how many to the odd positions (rounded down). State dfs(d, j, a, b): digits below d are placed, j is the sum still missing on the even positions, a and b are the free even and odd positions. Giving l copies of d to the even positions and r = cnt[d] - l to the odd ones is allowed when l * d <= j and r <= b, and it can be done in C(a, l) * C(b, r) ways. Multiply by the result for digit d + 1; when all digits are placed the state counts only if j, a, b are all 0. Because equal digits are placed as groups, no permutation is counted twice. Work modulo 10^9 + 7.
Complexity: about O(10 * n^2 * (n + 10)) time and O(10 * n^2 * n) memo space for the number of states, where n is the string length.
from collections import Counter
from math import comb
from functools import lru_cache
class Solution:
def countBalancedPermutations(self, num: str) -> int:
@lru_cache(None)
def dfs(i: int, j: int, a: int, b: int) -> int:
if i > 9:
return (j | a | b) == 0
if a == 0 and j:
return 0
ans = 0
for l in range(min(cnt[i], a) + 1):
r = cnt[i] - l
if 0 <= r <= b and l * i <= j:
t = comb(a, l) * comb(b, r) * dfs(i + 1, j - l * i, a - l, b - r)
ans = (ans + t) % mod
return ans
nums = list(map(int, num))
s = sum(nums)
if s % 2:
return 0
n = len(nums)
mod = 10**9 + 7
cnt = Counter(nums)
return dfs(0, s // 2, n // 2, (n + 1) // 2)