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-9 only
  • Important: Answer must be returned modulo 109 + 7

Visualization

Tap to expand
Balance Scale VisualizationEven PositionsIndices: 0, 2, 4...12Sum: 3Odd PositionsIndices: 1, 3, 5...3Sum: 3Input: "123"Total sum: 6Target per side: 3Possible? Yes!Valid Arrangements"132": 1+2=3, 3=3 โœ“"231": 2+1=3, 3=3 โœ“Count: 2DP SolutionCount arrangements withoutgenerating permutations
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.
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 18
62.0K Views
Medium Frequency
~35 min Avg. Time
1.5K 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