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
Count Balanced Permutations: "123" ExampleInput: 1233 digits, sum = 6Check all permutations for balance:123E:1+3=4, O:2 ✗132E:1+2=3, O:3 ✓213E:2+3=5, O:1 ✗231E:2+1=3, O:3 ✓312E:3+2=5, O:1 ✗321E:3+1=4, O:2 ✗Balanced permutations: 132, 231Result: 2Count found
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
Asked in
Google 25 Meta 20 Amazon 15
27.7K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen