Python 1170.py
class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
# f() according to problem
f = lambda w : w.count(min(w))
# precompute f(words)
freq = defaultdict(int)
for w in words:
freq[f(w)] += 1
cumulative = { 0 : len(words), 99999 : 0 } # edge cases
# cumulative version of freq
total = len(words)
for x in sorted(freq):
total -= freq[x]
cumulative[x] = total
# faster lookup via binary search
thresholds = list(sorted(cumulative.keys()))
# and finally start processing the queries
for q in queries:
value = f(q)
pos = bisect_right(thresholds, value) - 1
key = thresholds[pos]
yield cumulative[key]
Difficulty
and has an acceptance rate of about 64% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Hash Table
- Sorting
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation defines a Solution class with a single method numSmallerByFrequency. The method receives two lists of strings, queries and words, and returns a generator that yields, for each query string, the count of words whose “frequency value” is strictly greater than that of the query. The “frequency value” of a string is defined as the number of occurrences of its smallest character.
The algorithm proceeds in three logical phases: computing the frequency values for the words list, building a cumulative map that enables fast look-ups of how many words exceed a given frequency, and finally processing each query by locating the appropriate threshold via binary search.
Precomputation of Word Frequencies
f = lambda w: w.count(min(w))
freq = defaultdict(int)
for w in words:
freq[f(w)] += 1
A small inline function f captures the problem-specific definition of a string’s frequency. The loop iterates over every word, computes its frequency, and aggregates the counts in a defaultdict. This structure stores how many words share each distinct frequency value.
Construction of Cumulative Map
cumulative = {0: len(words), 99999: 0} # edge cases
total = len(words)
for x in sorted(freq):
total -= freq[x]
cumulative[x] = total
The cumulative dictionary is initialized with two sentinel entries. The key 0 maps to the total number of words, representing the count of words with frequency greater than any negative value. The key 99999 maps to 0, covering queries whose frequency exceeds the maximum possible word frequency.
The loop walks the sorted frequency keys in ascending order. At each step it subtracts the count of the current frequency from a running total, then records the remaining total under the current key. After the loop, cumulative[v] holds the number of words whose frequency is strictly greater than v.
thresholds = list(sorted(cumulative.keys()))
The sorted list of keys, named thresholds, is prepared for binary search. It contains all distinct frequency values plus the two sentinel keys.
Query Processing
for q in queries:
value = f(q)
pos = bisect_right(thresholds, value) - 1
key = thresholds[pos]
yield cumulative[key]
Each query string is transformed into its frequency value using the same f function. bisect_right locates the insertion point for this value in the ordered thresholds list; subtracting one yields the index of the greatest threshold that does not exceed the query’s frequency. The corresponding cumulative count is then yielded.
Edge Cases
The sentinel entries in cumulative guarantee correct results for queries whose frequency lies outside the range of frequencies observed in words. A query with a frequency lower than the smallest word frequency will map to the key 0, returning the total number of words. Conversely, a query with a frequency higher than any word frequency will map to the key 99999, yielding 0. This design eliminates the need for explicit boundary checks during binary search.
The use of defaultdict(int) ensures that missing frequency keys are treated as zero without raising exceptions, which gracefully handles cases where words may be empty or contain strings with identical frequencies.
Performance Optimizations
The algorithm avoids recomputing the frequency of each word multiple times by storing the results in freq. The cumulative map is built in a single pass over the sorted frequency keys, turning a potentially quadratic lookup into a constant-time retrieval per query. Binary search via bisect_right reduces the per-query search cost to logarithmic time relative to the number of distinct frequency values, which is typically far smaller than the total number of words. The final loop yields results lazily, allowing the caller to consume the output incrementally without constructing an intermediate list.
ELI5 - Simplified Explanation
Imagine you have two piles of toys. One pile contains long lists of words, and the other pile contains short mystery words. You want to see how many words from the big pile sound more exciting than the mystery words. First, the computer looks at each word and finds the very smallest letter in it. It then counts how many times that tiny letter appears. This count is a special number for that word.
The computer does this for every word in the big pile and keeps a tally of how many words have each count. It organizes this information in a neat way so it can quickly compare numbers. Now, the computer looks at each mystery word from the small pile. It finds the tiny letter count for the mystery word, just like before.
Then it looks at its organized list to see how many words from the other pile have a count that is larger than the mystery word's count. It uses a clever trick of dancing through the list to find the right answer very quickly. It keeps doing this for every mystery word in your list until every single one has been checked.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| DimitrisJim | C | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| DimitrisJim | C | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 2932: Maximum Strong Pair XOR I
- problem 731: My Calendar II
- problem 792: Number of Matching Subsequences
- problem 820: Short Encoding of Words
- problem 911: Online Election
- problem 950: Reveal Cards In Increasing Order
- problem 1023: Camelcase Matching
- problem 1038: Binary Search Tree to Greater Sum Tree
- problem 1171: Remove Zero Sum Consecutive Nodes from Linked List
- problem 1696: Jump Game VI
- problem 2327: Number of People Aware of a Secret
- problem 432: All O`one Data Structure
- problem 732: My Calendar III
- problem 1044: Longest Duplicate Substring
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality