Compare Strings by Frequency of the Smallest Character — LeetCode 1170 Python Solution

MediumArrayHash TableStringBinary SearchSorting
Problem
#1170
Reading time
2 min

The 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.

Example

Input
queries = ["cbd"], words = ["zaaaz"]
Output
[1]
Explanation
On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").

Python solution

Python
class Solution:
    def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
        def f(s: str) -> int:
            cnt = Counter(s)
            return next(cnt[c] for c in ascii_lowercase if cnt[c])

        n = len(words)
        nums = sorted(f(w) for w in words)
        return [n - bisect_right(nums, f(q)) for q in queries]

Complexity

MeasureComplexity
TimeO((n + q) \times M)
SpaceO(n) auxiliary

Pattern: Binary Search

Halve the search space each step — over an array, or over the answer itself. LeetCode 1170. Compare Strings by Frequency of the Smallest Character is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.

The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1170. Compare Strings by Frequency of the Smallest Character?
LeetCode 1170. Compare Strings by Frequency of the Smallest Character is rated Medium on LeetCode.
What is the time complexity of LeetCode 1170. Compare Strings by Frequency of the Smallest Character?
The Python solution on this page runs in O((n + q) \times M).
What is the space complexity of LeetCode 1170. Compare Strings by Frequency of the Smallest Character?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1170. Compare Strings by Frequency of the Smallest Character cover?
LeetCode 1170. Compare Strings by Frequency of the Smallest Character is tagged Array, Hash Table, String, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview