Approach
Sorting and greedy selection
For Compare Strings by Frequency of the Smallest Character, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 44 lines of Java from the credited upstream file 1170.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] numSmallerByFrequency(String[] queries, String[] words) {3 int[] ans = new int[queries.length];4 int[] wordsFreq = new int[words.length];5 6 for (int i = 0; i < words.length; ++i)7 wordsFreq[i] = f(words[i]);8 Arrays.sort(wordsFreq);9 10 for (int i = 0; i < queries.length; ++i) {11 final int freq = f(queries[i]);12 ans[i] = words.length - firstGreater(wordsFreq, 0, wordsFreq.length, freq);13 }14 15 return ans;16 }17 18 private int f(final String word) {19 int count = 0;20 char currentChar = 'z' + 1;21 22 for (final char c : word.toCharArray())23 if (c < currentChar) {24 currentChar = c;25 count = 1;26 } else if (c == currentChar) {27 ++count;28 }29 30 return count;31 }32 33 private int firstGreater(int[] nums, int l, int r, int value) {34 while (l < r) {35 final int m = (l + r) / 2;36 if (nums[m] > value)37 r = m;38 else39 l = m + 1;40 }41 return l;42 }43}44