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 arrayanswer, where eachanswer[i]is the answer to theithquery.
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").
For each word, compute the frequency of its smallest character. Sort these frequencies. For each query, compute its smallest character frequency and count how many word frequencies are greater using binary search.
classSolution {
funnumSmallerByFrequency(queries: Array<String>, words: Array<String>): IntArray {
funf(s: String): Int {
var mn = 'z'; var cnt = 0for (c in s) {
if (c < mn) { mn = c; cnt = 1 }
elseif (c == mn) cnt++ }
return cnt
}
val ws = words.map { f(it) }.sorted()
return queries.map { q ->val fq = f(q)
var l = 0; var r = ws.size
while (l < r) {
val m = (l + r) / 2if (ws[m] <= fq) l = m + 1else r = m
}
ws.size - l
}.toIntArray()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defnumSmallerByFrequency(self, queries: list[str], words: list[str]) -> list[int]:
deff(s: str) -> int:
mn = min(s)
return s.count(mn)
ws = sorted(f(w) for w in words)
ans = []
for q in queries:
fq = f(q)
l, r =0, len(ws)
while l < r:
m = (l + r) //2if ws[m] <= fq:
l = m +1else:
r = m
ans.append(len(ws) - l)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnnum_smaller_by_frequency(queries: Vec<String>, words: Vec<String>) -> Vec<i32> {
fnf(s: &str) -> i32 {
let mn = s.chars().min().unwrap();
s.chars().filter(|&c| c == mn).count() asi32 }
letmut ws: Vec<i32>= words.iter().map(|w| f(w)).collect();
ws.sort();
queries.iter().map(|q| {
let fq = f(q);
let l = ws.partition_point(|&x| x <= fq);
(ws.len() - l) asi32 }).collect()
}
}