LeetCode 1170: Compare Strings by Frequency of the Smallest Character Solution
Master LeetCode problem 1170 (Compare Strings by Frequency of the Smallest Character), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1170. Compare Strings by Frequency of the Smallest Character
Problem Explanation
Explanation:
To solve this problem, we need to calculate the frequency of the lexicographically smallest character in each word and then compare this frequency with the frequency of the smallest character in the query. For each query, we iterate through all the words and count the number of words where the frequency of the query's smallest character is less than the frequency of the smallest character in the word.
- Calculate the frequency of the smallest character in each word.
- For each query, compare the query's frequency with the frequency of the smallest character in each word.
- Count the number of words where the query's frequency is less than the word's frequency.
Time Complexity: O(n * m), where n is the number of words and m is the maximum length of a word. Space Complexity: O(n), where n is the number of words.
:
Solution Code
class Solution {
public int[] numSmallerByFrequency(String[] queries, String[] words) {
int[] wordFreq = new int[words.length];
int[] queryFreq = new int[queries.length];
int[] result = new int[queries.length];
for (int i = 0; i < words.length; i++) {
wordFreq[i] = calculateFrequency(words[i]);
}
for (int i = 0; i < queries.length; i++) {
queryFreq[i] = calculateFrequency(queries[i]);
}
for (int i = 0; i < queryFreq.length; i++) {
for (int j = 0; j < wordFreq.length; j++) {
if (queryFreq[i] < wordFreq[j]) {
result[i]++;
}
}
}
return result;
}
private int calculateFrequency(String word) {
char minChar = 'z';
int minCharCount = 0;
for (char c : word.toCharArray()) {
if (c < minChar) {
minChar = c;
minCharCount = 1;
} else if (c == minChar) {
minCharCount++;
}
}
return minCharCount;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1170 (Compare Strings by Frequency of the Smallest Character)?
This page provides optimized solutions for LeetCode problem 1170 (Compare Strings by Frequency of the Smallest Character) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1170 (Compare Strings by Frequency of the Smallest Character)?
The time complexity for LeetCode 1170 (Compare Strings by Frequency of the Smallest Character) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1170 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1170 in Java, C++, or Python.