LeetCode- 1170. Compare Strings by Frequency of the Smallest Character

1 minute read

Problem statement :-

Let’s define a function f(s) over a non-empty string s, which calculates the frequency of the smallest character in s. For example, if s = “dcce” then f(s) = 2 because the smallest character is “c” and its frequency is 2.

Now, given string arrays queries and words, return an integer array answer, where each answer[i] is the number of words such that f(queries[i]) < f(W), where W is a word in words.

Example

Input: queries = ["cbd"], words = ["zaaaz"]
Output: [1]

Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
Output: [1,2]

Solution

As the input are two list we have to return list which contains the count of occurrences where f(query) < f(word) for every (query, word) combination that can be made from the list of queries and words. As in the example two we have 2 queries and 4 words so we have following combination

all_comb = [("bbb","a"), ("bbb","aa"), ("bbb","aaa"), ("bbb","aaaa"),
("cc","a"), ("cc","aa"), ("cc","aaa"), ("cc","aaaa")]

Out of which only 1 pair satisfies f(query) < f(word) this condition for query 1 and 2 pair for query2. Note that the resulting list length will be same as the length of the queries list.

def string_freq(queries, words):
    queries_count = [s.count(min(s)) for s in queries]
    word_count = [w.count(min(w)) for w in words]
    answer = [sum(q < w for w in word_count) for q in queries_count]

    return answer

I hope this explanation and solution helped you.