Solving Leetcode Interviews in Seconds with AI: Count the Number of Consistent Strings
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1684" 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
You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent strings in the array words. Example 1: Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"] Output: 2 Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'. Example 2: Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"] Output: 7 Explanation: All strings are consistent. Example 3: Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"] Output: 4 Explanation: Strings "cc", "acd", "ac", and "d" are consistent. Constraints: 1 <= words.length <= 104 1 <= allowed.length <= 26 1 <= words[i].length <= 10 The characters in allowed are distinct. words[i] and allowed contain only lowercase English letters.
Explanation
Here's a breakdown of the approach, followed by the Python code:
Use a Set for Efficient Lookup: Convert the
allowedstring into a set. This allows for O(1) average-case time complexity to check if a character is present in the allowed characters.Iterate and Check Consistency: Iterate through each word in the
wordsarray. For each word, check if every character in the word is present in theallowedset. If all characters are present, increment the consistent string count.Early Exit (Optimization): If an inconsistent character is found in a word, immediately move on to the next word in the array, avoiding unnecessary character checks.
Runtime & Storage Complexity:
- Runtime Complexity: O(n * m), where n is the number of words and m is the maximum length of a word.
- Storage Complexity: O(1). The set used to store allowed characters will have a maximum size of 26 (since there are at most 26 distinct characters, lowercase English letters) - i.e. constant storage.
Code
def countConsistentStrings(allowed: str, words: list[str]) -> int:
"""
Counts the number of consistent strings in the array words.
A string is consistent if all characters in the string appear in the string allowed.
"""
allowed_set = set(allowed)
consistent_count = 0
for word in words:
is_consistent = True
for char in word:
if char not in allowed_set:
is_consistent = False
break # Optimization: Exit inner loop if inconsistent
if is_consistent:
consistent_count += 1
return consistent_count