Compare Strings by Frequency of the Smallest Character - Problem

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 ith query.

Input & Output

Example 1 — Basic Case
$ Input: words = ["cbd"], queries = ["aa"]
Output: [0]
💡 Note: f("aa") = 2 (frequency of 'a'), f("cbd") = 1 (frequency of 'b'). Since 2 > 1, there are 0 words where f("aa") < f(word).
Example 2 — Multiple Words
$ Input: words = ["aa","aaa","cccc"], queries = ["cbd"]
Output: [3]
💡 Note: f("cbd") = 1, f("aa") = 2, f("aaa") = 3, f("cccc") = 4. Since 1 < 2, 1 < 3, and 1 < 4, all 3 words satisfy the condition.
Example 3 — Mixed Results
$ Input: words = ["bbb","cc"], queries = ["aaa","bb"]
Output: [0,1]
💡 Note: f("aaa") = 3, f("bb") = 2, f("bbb") = 3, f("cc") = 2. For "aaa": 3 < 3? No, 3 < 2? No, so count = 0. For "bb": 2 < 3? Yes, 2 < 2? No, so count = 1.

Constraints

  • 1 ≤ queries.length ≤ 2000
  • 1 ≤ words.length ≤ 2000
  • 1 ≤ queries[i].length, words[i].length ≤ 10
  • queries[i][j], words[i][j] are lowercase English letters

Visualization

Tap to expand
Compare Strings by Frequency of Smallest Character INPUT words array: "cbd" queries array: "aa" Function f(s): Count frequency of smallest character in string Calculations: f("cbd") = 1 (smallest='b', count=1) f("aa") = 2 (smallest='a', count=2) ALGORITHM STEPS 1 Compute f(W) for words f("cbd") = 1 2 Compute f(q) for queries f("aa") = 2 3 Compare f(q) with f(W) Is f("aa") < f("cbd")? 4 Count matches 2 < 1? NO (false) Comparison Table Query Word Result f=2 f=1 2 !< 1 Count = 0 FINAL RESULT Output Array: [0] Explanation: For query "aa": f("aa") = 2 f("cbd") = 1 2 is NOT less than 1 OK - Answer: [0] 0 words satisfy condition answer[0] = 0 Key Insight: Pre-compute f(W) values for all words, then use binary search or counting sort for efficient queries. For each query, count how many words have f(W) > f(query). Time complexity: O(n log n + m log n). TutorialsPoint - Compare Strings by Frequency of the Smallest Character | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen