From 39a357bd3917bff0479fb0760007c7c970a66bfb Mon Sep 17 00:00:00 2001 From: Siddhartha Dutta Date: Sun, 29 Dec 2024 15:22:33 +0000 Subject: [PATCH] Dec 29 --- ...Form a Target String Given a Dictionary.py | 35 +++++++++++++++++++ .../README.md | 6 ++-- 2 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 2024-12-December-LeetCoding-Challenge/Number of Ways to Form a Target String Given a Dictionary.py diff --git a/2024-12-December-LeetCoding-Challenge/Number of Ways to Form a Target String Given a Dictionary.py b/2024-12-December-LeetCoding-Challenge/Number of Ways to Form a Target String Given a Dictionary.py new file mode 100644 index 0000000..39eebfc --- /dev/null +++ b/2024-12-December-LeetCoding-Challenge/Number of Ways to Form a Target String Given a Dictionary.py @@ -0,0 +1,35 @@ +from collections import Counter +from functools import lru_cache +from typing import List + + +class Solution: + def numWays(self, words: List[str], target: str) -> int: + count = [Counter() for _ in range(len(words[0]))] + for word in words: + for idx, ch in enumerate(word): + count[idx][ch] += 1 + + @lru_cache(None) + def dfs(i: int = 0, j: int = 0) -> int: + if i == len(target): + return 1 + if j == len(words[0]): + return 0 + return (dfs(i, j+1) + dfs(i+1, j+1) * count[j][target[i]]) % int(1e9 + 7) + + return dfs() + + +def main(): + words = ['acca', 'bbbb', 'caca'] + target = 'aba' + assert Solution().numWays(words, target) == 6 + + words = ['abba', 'baab'] + target = 'bab' + assert Solution().numWays(words, target) == 4 + + +if __name__ == '__main__': + main() diff --git a/2024-12-December-LeetCoding-Challenge/README.md b/2024-12-December-LeetCoding-Challenge/README.md index ec8c166..b69d7bc 100644 --- a/2024-12-December-LeetCoding-Challenge/README.md +++ b/2024-12-December-LeetCoding-Challenge/README.md @@ -30,8 +30,8 @@ | December 25 | [515. Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/) | Medium | Solved | | December 26 | [494. Target Sum](https://leetcode.com/problems/target-sum/) | Medium | Solved | | December 27 | [1014. Best Sightseeing Pair](https://leetcode.com/problems/best-sightseeing-pair/) | Medium | Unsolved | -| December 28 | []() | | | -| December 29 | []() | | | +| December 28 | [689. Maximum Sum of 3 Non-Overlapping Subarrays](https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/) | Hard | Unsolved | +| December 29 | [1639. Number of Ways to Form a Target String Given a Dictionary](https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/) | Hard | Unsolved | | December 30 | []() | | | | December 31 | []() | | | @@ -40,4 +40,4 @@ | --- | --- | --- | --- | | Easy | 5 | 5 | 0 | | Medium | 19 | 12 | 7 | -| Hard | 3 | 0 | 3 | +| Hard | 5 | 0 | 5 |