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
Count Number of Balanced Permutations INPUT String: num = "123" 1 idx 0 2 idx 1 3 idx 2 Even: 0, 2 Odd: 1 Digits: [1, 2, 3] Total sum: 1+2+3 = 6 Target per side: 3 Balanced means: sum(even idx) = sum(odd idx) ALGORITHM STEPS 1 Count Positions Even: 2 slots, Odd: 1 slot 2 DP for Combinations Find ways to get sum=3 3 Multinomial Coeff Handle digit repetition 4 Count Permutations Multiply arrangements Valid Selections: Even idx: {1,2} Odd idx: {3} Sum: 1+2=3, 3=3 OK FINAL RESULT Balanced Permutations: 1 3 2 OK 1+2=3, 3=3 2 3 1 OK 2+1=3, 3=3 Output: 2 2 distinct balanced permutations found Result mod 10^9+7 Key Insight: Use combinatorial math: For string of length n, there are ceil(n/2) even positions and floor(n/2) odd positions. Count ways to select digits for each side that sum to totalSum/2 using DP, then multiply by arrangements using multinomial coefficients to handle duplicate digits. Total complexity: O(n * sum * n). TutorialsPoint - Count Number of Balanced Permutations | Combinatorial Mathematics
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