The Compare Strings by Frequency of the Smallest Character interview question gives you two arrays of strings: queries and words. For each string, you define a function f(s) that counts the frequency of the lexicographically smallest character in s. For each query string q, you need to find how many strings w in the words array satisfy f(q) < f(w).
Google uses this String interview pattern to test a candidate's ability to combine multiple simple tasks (character counting) with efficient searching (binary search). It tests whether you can optimize an O(Q * W) brute-force solution into a much faster O((Q + W) log W) or even O(Q + W) solution by using frequency counts.
This problem combines Frequency Counting and Binary Search.
f(w) for every word in the words array.f(q).upper_bound or bisect_right) on the sorted frequencies to find how many values are strictly greater than f(q).Queries: ["cbd"], Words: ["zaaaz", "abcd"]
f("cbd"): Smallest char is 'b'. Frequency of 'b' is 1.f("zaaaz"): Smallest char is 'a'. Frequency of 'a' is 3.f("abcd"): Smallest char is 'a'. Frequency of 'a' is 1.[3, 1]. Sorted: [1, 3].[1, 3] are > 1? Only one value (3).
Result: [1].Since the maximum frequency of a string is often small (e.g., the max length of a string is 10), you can use a "Frequency of Frequencies" array (size 11 or 12) and a suffix sum to answer queries in O(1) after O(W) preprocessing.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Points Inside the Square | Medium | Solve | |
| Find And Replace in String | Medium | Solve | |
| Group Anagrams | Medium | Solve | |
| Alert Using Same Key-Card Three or More Times in a One Hour Period | Medium | Solve | |
| Before and After Puzzle | Medium | Solve |