Find Words That Can Be Formed by Characters — LeetCode 1160 Python Solution

EasyArrayHash TableStringCounting
Problem
#1160
Pattern
Hash Map
Reading time
2 min

The problem

You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once for each word in words).

Example

Input
words = ["cat","bt","hat","tree"], chars = "atach"
Output
6
Explanation
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Python solution

Python
class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        cnt = Counter(chars)
        ans = 0
        for w in words:
            wc = Counter(w)
            if all(cnt[c] >= v for c, v in wc.items()):
                ans += len(w)
        return ans

Complexity

MeasureComplexity
TimeO(L)
SpaceO(C) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1160. Find Words That Can Be Formed by Characters is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1160. Find Words That Can Be Formed by Characters?
LeetCode 1160. Find Words That Can Be Formed by Characters is rated Easy on LeetCode.
What is the time complexity of LeetCode 1160. Find Words That Can Be Formed by Characters?
The Python solution on this page runs in O(L).
What is the space complexity of LeetCode 1160. Find Words That Can Be Formed by Characters?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 1160. Find Words That Can Be Formed by Characters cover?
LeetCode 1160. Find Words That Can Be Formed by Characters is tagged Array, Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview