Compare Strings by Frequency of the Smallest Character Problem
Description
LeetCode Problem 1170.
Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.
You are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words.
Return an integer array answer, where each answer[i] is the answer to the i^th query.
Example 1:
Input: queries = ["cbd"], words = ["zaaaz"]
Output: [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").
Example 2:
Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
Output: [1,2]
Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
Constraints:
1 <= queries.length <= 20001 <= words.length <= 20001 <= queries[i].length, words[i].length <= 10queries[i][j],words[i][j]consist of lowercase English letters.
Solution
Approach: Sort the Word Frequencies + Binary Search
First, f(s) is easy to compute: find the smallest letter in s and count how often it appears (or count all 26 letters and take the first non-zero count).
For each query q we need the number of words W with f(q) < f(W). Comparing against all words for every query is O(q * n). Instead, compute f(W) for all words once and sort these values. The words with f(W) > f(q) then form a suffix of the sorted list, starting at the first value greater than f(q), which a binary search (upper bound) finds. The answer is the number of values after that point.
Watch the strict comparison: words with f(W) == f(q) must not be counted, which is why we search for the first value greater than f(q), not the first one greater or equal.
Complexity: O((n + q) * L + n log n + q log n) time, where L ≤ 10 is the length of a string, and O(n) extra space for the sorted frequencies.
from bisect import bisect_right
class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
def f(s: str) -> int:
return s.count(min(s)) # frequency of the smallest letter
freqs = sorted(f(w) for w in words)
n = len(freqs)
# Words with f(W) > f(q) are exactly the ones after the last value <= f(q).
return [n - bisect_right(freqs, f(q)) for q in queries]