#1170
Compare Strings by Frequency of the Smallest Character
MediumArrayHash TableStringBinary SearchSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m log m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + m log m)Space O(n)
By precomputing the frequencies of the smallest characters in the words and sorting them, we can efficiently answer each query using binary search. This reduces the number of comparisons needed.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the frequency of the smallest character for each word and store these frequencies in a list.
- 2Step 2: Sort the list of frequencies.
- 3Step 3: For each query, calculate its frequency and use binary search to find how many frequencies in the sorted list are greater than this frequency.
solution.py5 lines
1def f(s): return s.count(min(s))
2
3def numSmallerByFrequency(queries, words):
4 freq = sorted(f(w) for w in words)
5 return [len(freq) - bisect.bisect_right(freq, f(q)) for q in queries]ℹ
Complexity note: The sorting step takes O(n log n) for the words and O(m log m) for the queries, where n is the number of words and m is the number of queries. The space complexity accounts for storing the frequencies.
- 1Understanding how to compute character frequencies is crucial for this problem.
- 2Sorting and binary search can significantly reduce the time complexity of the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.