Ctrl K

Balanced Digit Shuffles

Hard
You are given a string digits of decimal digits. Call a string balanced if the sum of its digits at even positions (0, 2, 4, …) equals the sum of its digits at odd positions (1, 3, 5, …). Return how many distinct strings that are rearrangements of digits are balanced. Identical strings count once. The answer can be large, so return it modulo 10⁹ + 7.
Example 1
digits="242" → 1

There are three distinct arrangements: 224, 242 and 422. Only 242 balances: 2 + 2 at the even positions against 4 at the odd one.

Example 2
digits="1203" → 8

The digits must split into two pairs summing to 3: {1, 2} and {0, 3}. Either pair can take the even positions (2 ways), and each pair can be ordered in 2 ways: 2 · 2 · 2 = 8 in total.

Example 3
digits="115" → 0

The digit sum 7 is odd and cannot be split evenly, so the answer is 0.

Constraints
  • 2 ≤ len(digits) ≤ 80
  • digits contains only the characters 0 through 9
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCollapsing by Counting Ones HardVowels Across All Pieces MediumTasters and the Spoiled Cask HardNumbers From Working Keys HardRadio Show Without Quick Repeats Hard
loading Python…
Input
digits="242"
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 114 tests on the server, hidden ones included.