Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Number of Valid Words for Each Puzzle

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1178" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

With respect to a given puzzle string, a word is valid if both the following conditions are satisfied: word contains the first letter of puzzle. For each letter in word, that letter is in puzzle. For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage", while invalid words are "beefed" (does not include 'a') and "based" (includes 's' which is not in the puzzle). Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i]. Example 1: Input: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] Output: [1,1,3,2,4,0] Explanation: 1 valid word for "aboveyz" : "aaaa" 1 valid word for "abrodyz" : "aaaa" 3 valid words for "abslute" : "aaaa", "asas", "able" 2 valid words for "absoryz" : "aaaa", "asas" 4 valid words for "actresz" : "aaaa", "asas", "actt", "access" There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'. Example 2: Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"] Output: [0,1,3,2,0] Constraints: 1 <= words.length <= 105 4 <= words[i].length <= 50 1 <= puzzles.length <= 104 puzzles[i].length == 7 words[i] and puzzles[i] consist of lowercase English letters. Each puzzles[i] does not contain repeated characters.

Explanation

Here's the breakdown of the approach, complexity, and the Python code:

  • High-Level Approach:

    • Represent each word and puzzle as a bitmask, where each bit corresponds to a letter of the alphabet.
    • Iterate through the puzzles, and for each puzzle, iterate through the words. Check if the word's bitmask satisfies the puzzle's bitmask and contains the first letter of the puzzle.
    • Optimize by pre-calculating the bitmasks for all words to avoid repeated calculations.
  • Complexity:

    • Runtime Complexity: O(N + M * K), where N is the number of words, M is the number of puzzles, and K is the average length of words. Due to the constraints on puzzle length (always 7), the checking part is quite efficient as it only iterates once through all words for a puzzle. The complexity comes from computing masks for all words at the begining.
    • Storage Complexity: O(N), where N is the number of words (for storing word masks).

Code

    def findNumOfValidWords(words, puzzles):
    """
    Finds the number of valid words for each puzzle.

    Args:
        words: A list of words.
        puzzles: A list of puzzles.

    Returns:
        A list of integers, where each element represents the number of valid words for the corresponding puzzle.
    """

    word_masks = {}
    for word in words:
        mask = 0
        for char in set(word):  # Use set to avoid duplicate letters within a word affecting the mask
            mask |= (1 << (ord(char) - ord('a')))
        if mask not in word_masks:
            word_masks[mask] = 0
        word_masks[mask] += 1

    result = []
    for puzzle in puzzles:
        count = 0
        first_char_mask = (1 << (ord(puzzle[0]) - ord('a')))
        puzzle_mask = 0
        for char in puzzle:
            puzzle_mask |= (1 << (ord(char) - ord('a')))

        for word_mask, word_count in word_masks.items():
            if (word_mask & puzzle_mask) == word_mask and (word_mask & first_char_mask):
                count += word_count
        result.append(count)

    return result

More from this blog

C

Chatmagic blog

2894 posts