Skip to main content
Back to problems
#1772
Medium Algorithms

Sort features by popularity

Array Hash Table String Sorting
66.4% acceptance
Mar 31, 2026
92
43
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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn sort_features(features: Vec<String>, responses: Vec<String>) -> Vec<String> {
    use std::collections::{HashMap, HashSet};
    let mut count: HashMap<&str, usize> = HashMap::new();
    for response in &responses {
      let words: HashSet<&str> = response.split_whitespace().collect();
      for feature in &features {
        if words.contains(feature.as_str()) {
          *count.entry(feature.as_str()).or_insert(0) += 1;
        }
      }
    }
    let mut indexed: Vec<(usize, &String)> = features.iter().enumerate().collect();
    indexed.sort_by(|a, b| {
      let ca = count.get(a.1.as_str()).unwrap_or(&0);
      let cb = count.get(b.1.as_str()).unwrap_or(&0);
      cb.cmp(ca).then(a.0.cmp(&b.0))
    });
    indexed.into_iter().map(|(_, f)| f.clone()).collect()
  }
}