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 .
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.
This is a Dynamic Programming problem with a combinatorial twist.
total_sum / 2.dp(digit_index, current_even_sum, even_slots_left).Suppose digits are "123". Sum = 6. Target sum = 3. Slots: 2 even, 1 odd (for a 3-digit number).
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.
When dealing with permutations of items with duplicates, always think about the multinomial coefficient formula: . In DP, you can incorporate this by multiplying the current count by .
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count K-Reducible Numbers Less Than N | Hard | Solve | |
| Vowels of All Substrings | Medium | Solve | |
| Number of Ways to Rearrange Sticks With K Sticks Visible | Hard | Solve | |
| Poor Pigs | Hard | Solve | |
| Count the Number of Powerful Integers | Hard | Solve |