Similar Problems
Similar Problems not available
Compare Strings By Frequency Of The Smallest Character - Leetcode Solution
Companies:
LeetCode: Compare Strings By Frequency Of The Smallest Character Leetcode Solution
Difficulty: Medium
Topics: hash-table binary-search string array sorting
Problem Statement:
You are given an array of strings words and a string query. Let's define a function count(word) that returns the frequency of the smallest character in word.
For example, count("aab") = 1 because the smallest character is 'a' and it appears 1 time. Now, you are given a string query. You need to output for each query query[i], the number of words in words such that count(words[j]) == count(query[i]).
Example:
Input: words = ["cbd"], queries = ["zaaaz"] Output: [1] Explanation: On the first query we have count("zaaaz") = 1, count("cbd") = 1 so the answer is 1.
Solution:
First we need to create a function that counts the frequency of the smallest element in a string. We can do that by looping through all the characters in the string and keeping track of the count of the smallest character. Then we return the count of the smallest character.
def count(s): minChar = min(s) count = 0 for c in s: if c == minChar: count += 1 return count
Now we can loop through the query strings and count their smallest character frequency. Then we can loop through the words and count their smallest character frequency and check if it matches the query string's smallest character frequency. If it does, we increment the count.
def numSmallerByFrequency(words, queries): ans = [] for query in queries: qFreq = count(query) count = 0 for word in words: wFreq = count(word) if wFreq > qFreq: count += 1 ans.append(count) return ans
We can test our function with the given test case:
words = ["cbd"] queries = ["zaaaz"] print(numSmallerByFrequency(words, queries))
Output: [1]
We can test this function with more test cases too.
Example:
words = ["cbd", "ccc"] queries = ["zaaaz", "cccccc"] print(numSmallerByFrequency(words, queries))
Output:
[1, 2]
Explanation: For the first query, count("zaaaz") = 1 and count("cbd") = 1, so the answer is 1. For the second query, count("cccccc") = 6 and count("cbd") = 1 and count("ccc") = 3, so the answer is 2.
Compare Strings By Frequency Of The Smallest Character Solution Code
1