Sort Features by Popularity Problem
Description
LeetCode Problem 1772.
You are given a string array features where features[i] is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array responses, where each responses[i] is a string containing space-separated words.
The popularity of a feature is the number of responses[i] that contain the feature. You want to sort the features in non-increasing order by their popularity. If two features have the same popularity, order them by their original index in features. Notice that one response could contain the same feature multiple times; this feature is only counted once in its popularity.
Return the features in sorted order.
Example 1:
Input: features = ["cooler","lock","touch"], responses = ["i like cooler cooler","lock touch cool","locker like touch"]
Output: ["touch","cooler","lock"]
Explanation: appearances("cooler") = 1, appearances("lock") = 1, appearances("touch") = 2. Since "cooler" and "lock" both had 1 appearance, "cooler" comes first because "cooler" came first in the features array.
Example 2:
Input: features = ["a","aa","b","c"], responses = ["a","a aa","a a a a a","b a"]
Output: ["a","aa","b","c"]
Constraints:
1 <= features.length <= 10^41 <= features[i].length <= 10featurescontains no duplicates.features[i]consists of lowercase letters.1 <= responses.length <= 10^21 <= responses[i].length <= 10^3responses[i]consists of lowercase letters and spaces.responses[i]contains no two consecutive spaces.responses[i]has no leading or trailing spaces.
Solution
Approach: Hash Map + Custom Sort
The popularity of a feature is the number of responses that contain it, so a word repeated inside one response counts only once.
For every response, collect its distinct words in a set and add one to a counter for each of them. Then sort the features by popularity in descending order. Python's sort is stable, so features with equal popularity keep their original order; in the other languages we sort indices and break ties by the smaller index.
Complexity: O(L + n log n) time, where L is the total length of the responses and n is the number of features, and O(L) extra space.
from collections import Counter
class Solution:
def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]:
cnt = Counter()
for s in responses:
for w in set(s.split()):
cnt[w] += 1
return sorted(features, key=lambda w: -cnt[w])