Leetcode 1160: Find Words That Can Be Formed by Characters

grid47
grid47
Exploring patterns and algorithms
Jul 14, 2024 6 min read

You are given an array of strings words and a string chars. A string is considered ‘good’ if it can be formed using characters from chars where each character can be used at most once. Your task is to return the sum of the lengths of all ‘good’ strings in words.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of strings `words` and a string `chars`.
Example: Input: words = ["dog", "cat", "bat", "tree"], chars = "atagcbd"
Constraints:
• 1 <= words.length <= 1000
• 1 <= words[i].length, chars.length <= 100
• words[i] and chars consist of lowercase English letters
Output: The output should be an integer representing the sum of lengths of all good strings in the array `words`.
Example: Output: 6
Constraints:
• The output should be the total length of all 'good' strings.
Goal: The goal is to calculate the total length of all good strings in `words` that can be formed using characters from `chars`.
Steps:
• Create a frequency array for the characters in `chars`.
• For each word in `words`, check if it can be formed using characters from `chars`.
• If the word can be formed, add its length to the result.
Goal: The solution should handle arrays with up to 1000 words and strings of up to 100 characters efficiently.
Steps:
• 1 <= words.length <= 1000
• 1 <= words[i].length, chars.length <= 100
• words[i] and chars consist of lowercase English letters
Assumptions:
• Each character in `chars` can be used at most once to form a word.
• The characters in `chars` and `words` are all lowercase English letters.
Input: Input: words = ["dog", "cat", "bat", "tree"], chars = "atagcbd"
Explanation: The strings 'dog' and 'cat' can be formed using characters from 'atagcbd'. The total length is 3 + 3 = 6.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus