Problem statement

https://leetcode.com/problems/sort-features-by-popularity/

Solution

All we need to do is go through responses and collect all words, then sort then by frequencies.

Complexity

Time complexity is O(M + N*log N), where M is total length of responses and M is total length of F.

Code

class Solution:
    def sortFeatures(self, F, responses):
        cnt = Counter()
        for resp in responses:
            for word in set(resp.split()):
                cnt[word] += 1
                
        cands = sorted([(-cnt[f], i) for i, f in enumerate(F)])
        return [F[i] for _,i in cands]