Magicsheet logo

Count Number of Balanced Permutations

Hard
12.5%
Updated 8/1/2025

Count Number of Balanced Permutations

What is this problem about?

A permutation of digits is "balanced" if the sum of digits at even indices is equal to the sum of digits at odd indices. Given a string of digits, you need to find the number of unique balanced permutations. Since the answer can be very large, return it modulo 109+710^9 + 7.

Why is this asked in interviews?

This "Hard" problem is asked by Meta and Google to test proficiency in Combinatorics and Dynamic Programming (DP). It requires managing two constraints simultaneously: the total sum of digits (which must be split in half) and the number of available slots for even and odd indices. It also tests your ability to handle duplicate elements using multinomial coefficients.

Algorithmic pattern used

This is a Dynamic Programming problem with a combinatorial twist.

  1. Calculate the frequency of each digit (0-9) and the total sum of all digits.
  2. If the total sum is odd, no balanced permutation exists (return 0).
  3. Targeted sum for both even and odd indices is total_sum / 2.
  4. Define DP state: dp(digit_index, current_even_sum, even_slots_left).
  5. At each digit, decide how many instances of that digit to place in the remaining even-index slots.
  6. Use factorials and modular inverse to account for identical digits.

Example explanation

Suppose digits are "123". Sum = 6. Target sum = 3. Slots: 2 even, 1 odd (for a 3-digit number).

  • Target sum for 2 even slots: 3. Target sum for 1 odd slot: 3.
  • If even slots are filled with {1, 2}, sum is 3. Odd slot is {3}, sum is 3. (Balanced!)
  • Possible permutations: [1, 3, 2] and [2, 3, 1].
  • If even slots are filled with {3, 0}... (no zeros here). The DP counts these combinations efficiently.

Common mistakes candidates make

One major pitfall is failing to handle duplicate digits correctly in the counting logic. Another is not realizing that the number of even and odd indices is fixed based on the length of the string. Some candidates also struggle with the memory limits of a 3D DP table and need to optimize using a 2D table or iterative approach.

Interview preparation tip

When dealing with permutations of items with duplicates, always think about the multinomial coefficient formula: n!n1!n2!nk!\frac{n!}{n_1! n_2! \dots n_k!}. In DP, you can incorporate this by multiplying the current count by (total_available_slotsslots_chosen_for_this_digit)\binom{total\_available\_slots}{slots\_chosen\_for\_this\_digit}.

Similar Questions