↓Skip to main content
  1. LeetCode/

LeetCode 1160: Find Words That Can Be Formed by Characters

·1 min· ·
LeetCode Easy Array Hash-Table String Counting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-10-18

  • Submissions: Accepted ×3

Approach
#

Count chars once (Hash Table Template 1) and each word; an empty Counter(w) - C means every character suffices (as in LC 383), so add the word’s length.

My Solution
#

class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        have = Counter(chars)
        return sum(len(w) for w in words if not (Counter(w) - have))

Complexity
#

Time O(total characters), space O(k).

Mistakes to Avoid
#

  • Count chars once outside the loop; each word may use all of chars independently.

Interview Explanation
#

I count chars once, then check that each word’s needs do not exceed it, adding the lengths of formable words. Time is linear in the total length.

Related

LeetCode 819: Most Common Word
·2 mins
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 note: replace punctuation with spaces, lowercase, split, count, and pick the most frequent word not banned
LeetCode 804: Unique Morse Code Words
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 804 note: translate each word into a Morse string and count the distinct results with a set
LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row
LeetCode 1128: Number of Equivalent Domino Pairs
·2 mins
LeetCode Easy Array Hash-Table Counting
LeetCode 1128 note: normalize each domino to (small, large) as a key and count; a key with c dominoes yields c(c - 1) / 2 pairs
LeetCode 1189: Maximum Number of Balloons
·2 mins
LeetCode Easy Hash-Table String Counting
LeetCode 1189 note: each letter supports count // needed balloons, with l and o needed twice; take the minimum
LeetCode 1002: Find Common Characters
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 1002 note: count each word and intersect all Counters (minimum count per character), then expand