Problem 1170

Abstract / Summary

Compare two strings by counting how often the smallest character appears in each and return which string has more of those characters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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]
26 lines | 863 bytes | submitted November 23, 2023 | GitHub   35% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Hash Table
  • Sorting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.48 | σ = 1.62

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
28 links | 17 authors | 8 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

15 solutions   November 23, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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