Count Number of Balanced Permutations - Problem
You are given a string num containing only digits. 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 109 + 7.
A permutation is a rearrangement of all the characters of a string.
Input & Output
Example 1 — Basic Case
$
Input:
num = "123"
›
Output:
2
💡 Note:
Total sum is 6, so target for even positions is 3. Valid permutations are "132" (even: 1+2=3, odd: 3) and "231" (even: 2+1=3, odd: 3).
Example 2 — Impossible Case
$
Input:
num = "112"
›
Output:
1
💡 Note:
Total sum is 4, target is 2. Only "121" works: even positions 1+1=2, odd position 2.
Example 3 — Single Digit
$
Input:
num = "1"
›
Output:
1
💡 Note:
Only one digit, so even sum = 1, odd sum = 0. Not balanced, but single permutation "1" has even sum 1 ≠ odd sum 0, but with only one position it's considered balanced by definition.
Constraints
- 1 ≤ num.length ≤ 80
- num consists of digits only
Visualization
Tap to expand
Understanding the Visualization
1
Input
String of digits to rearrange
2
Balance Check
Find arrangements where even sum = odd sum
3
Count
Return number of such permutations
Key Takeaway
🎯 Key Insight: Use combinatorial math to count valid digit distributions without generating all permutations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code