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:
0
💡 Note:
Single digit "1" at position 0 (even). Even sum = 1, odd sum = 0. Since 1 ≠ 0, it's not balanced.
Constraints
- 1 ≤ num.length ≤ 80
- num consists of digits only
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code