Approach
Sorting and greedy selection
For Sort Features by Popularity, 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
- 23 lines of Java from the credited upstream file 1772.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 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 String[] sortFeatures(String[] features, String[] responses) {3 String[] ans = new String[features.length];4 int[][] featCount = new int[features.length][]; 5 Map<String, Integer> count = new HashMap<>();6 7 for (final String res : responses)8 for (final String token : new HashSet<>(Arrays.asList(res.split(" "))))9 count.merge(token, 1, Integer::sum);10 11 for (int i = 0; i < features.length; ++i)12 featCount[i] = new int[] {i, count.getOrDefault(features[i], 0)};13 14 Arrays.sort(featCount,15 Comparator.comparingInt((int[] a) -> - a[1]).thenComparingInt((int[] a) -> a[0]));16 17 for (int i = 0; i < features.length; ++i)18 ans[i] = features[featCount[i][0]];19 20 return ans;21 }22}23