Skip to content

Commit 4f511d9

Browse files
committed
May 09
1 parent 1407e39 commit 4f511d9

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from functools import lru_cache
2+
from collections import Counter
3+
from math import comb
4+
5+
6+
class Solution:
7+
MOD = 10**9 + 7
8+
9+
def countBalancedPermutations(self, num: str) -> int:
10+
count = Counter(map(int, num))
11+
total = sum(map(int, num))
12+
13+
@lru_cache(None)
14+
def dfs(i: int, odd: int, even: int, balance: int) -> int:
15+
if odd == 0 and even == 0 and balance == 0:
16+
return 1
17+
if i < 0 or odd < 0 or even < 0 or balance < 0:
18+
return 0
19+
20+
res = 0
21+
for j in range(0, count[i] + 1):
22+
res += comb(odd, j) * \
23+
comb(even, count[i] - j) * \
24+
dfs(i - 1, odd - j, even - count[i] + j, balance - i * j)
25+
return res % self.MOD
26+
27+
return 0 if total % 2 else dfs(9, len(num) - len(num) // 2, len(num) // 2, total // 2)
28+
29+
30+
def main():
31+
num = '123'
32+
assert Solution().countBalancedPermutations(num) == 2
33+
34+
num = '112'
35+
assert Solution().countBalancedPermutations(num) == 1
36+
37+
num = '12345'
38+
assert Solution().countBalancedPermutations(num) == 0
39+
40+
41+
if __name__ == '__main__':
42+
main()

2025-05-May-LeetCoding-Challenge/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
| May 06 | [1920. Build Array from Permutation](https://leetcode.com/problems/build-array-from-permutation/) | Easy | Solved |
1313
| May 07 | [3341. Find Minimum Time to Reach Last Room I](https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i/) | Medium | Solved |
1414
| May 08 | [3342. Find Minimum Time to Reach Last Room II](https://leetcode.com/problems/find-minimum-time-to-reach-last-room-ii/) | Medium | Solved |
15-
| May 09 | []() | | |
15+
| May 09 | [3343. Count Number of Balanced Permutations](https://leetcode.com/problems/count-number-of-balanced-permutations/) | Hard | Unsolved |
1616
| May 10 | []() | | |
1717
| May 11 | []() | | |
1818
| May 12 | []() | | |
@@ -42,4 +42,4 @@
4242
| --- | --- | --- | --- |
4343
| Easy | 2 | 2 | 0 |
4444
| Medium | 5 | 5 | 0 |
45-
| Hard | 1 | 1 | 0 |
45+
| Hard | 2 | 1 | 1 |

0 commit comments

Comments
 (0)