Count Number of Balanced Permutations - Problem
Imagine you're a mathematician arranging digits on a scale, where you need to balance the left side (even indices) against the right side (odd indices).
Given a string num containing only digits, your task is to count how many distinct permutations of this string are balanced. A permutation is considered balanced when:
- Sum of digits at even indices (0, 2, 4, ...) equals
- Sum of digits at odd indices (1, 3, 5, ...)
Example: For "123", the permutation "132" is balanced because position 0 has digit 1, position 1 has digit 3, position 2 has digit 2. So even sum = 1 + 2 = 3, odd sum = 3. They're equal!
Since the answer can be astronomically large, return it modulo 109 + 7.
Input & Output
example_1.py โ Basic Case
$
Input:
num = "123"
โบ
Output:
2
๐ก Note:
The balanced permutations are "132" (1+2=3, 3=3) and "231" (2+1=3, 3=3). Total sum is 6, so each side needs sum 3.
example_2.py โ Single Digit
$
Input:
num = "5"
โบ
Output:
0
๐ก Note:
With only one digit, we have even sum = 5 and odd sum = 0. Since 5 โ 0, no balanced permutation exists.
example_3.py โ All Zeros
$
Input:
num = "0000"
โบ
Output:
1
๐ก Note:
All permutations are identical "0000". Even sum = 0+0=0, odd sum = 0+0=0. Since 0=0, this single permutation is balanced.
Constraints
- 1 โค num.length โค 80
-
num consists of digits
0-9only - Important: Answer must be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Scale
Even positions (0,2,4...) go on left pan, odd positions (1,3,5...) go on right pan
2
Count Available Weights
Tally how many of each digit (0-9) we have available to place
3
Calculate Target Weight
Total weight must be even, and each pan needs exactly half the total
4
Use Smart Counting
Instead of trying every arrangement, use math to count valid distributions
Key Takeaway
๐ฏ Key Insight: Transform the permutation counting problem into a dynamic programming problem by tracking digit distributions between even and odd positions, avoiding the exponential cost of generating all permutations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code