Sort Features by Popularity - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: features = ["cooler","lock","touch"], responses = ["i love cooler cooler","lock touch cool","cooler lock"]
Output: ["cooler","lock","touch"]
💡 Note: cooler appears in 2 responses, lock appears in 2 responses, touch appears in 1 response. cooler and lock have same count but cooler has lower index (0 vs 1).
Example 2 — Different Popularity
$ Input: features = ["a","aa","aaa"], responses = ["a aa a","a aa","aaa","a"]
Output: ["a","aa","aaa"]
💡 Note: a appears in 3 responses, aa appears in 2 responses, aaa appears in 1 response. Sort by popularity: a > aa > aaa.
Example 3 — Tie Breaking
$ Input: features = ["x","y","z"], responses = ["x y","y z"]
Output: ["y","x","z"]
💡 Note: y appears in 2 responses, x and z each appear in 1 response. y comes first, then x before z due to original order.

Constraints

  • 1 ≤ features.length ≤ 104
  • 1 ≤ features[i].length ≤ 4
  • features[i] consists of lowercase letters
  • 1 ≤ responses.length ≤ 103
  • 1 ≤ responses[i].length ≤ 103
  • responses[i] consists of lowercase letters and spaces
  • responses[i] contains no two consecutive spaces
  • There are no duplicate features

Visualization

Tap to expand
Sort Features by PopularityFeatures["cooler","lock","touch"]User Responses"i love cooler cooler""lock touch cool""cooler lock"Popularity Countcooler: 2 responseslock: 2 responsestouch: 1 responseSorted Result["cooler", "lock", "touch"]Tie-break: cooler index 0 < lock index 1
Understanding the Visualization
1
Input
Features array and user responses mentioning features
2
Count
Count unique mentions of each feature across responses
3
Sort
Rank features by popularity, tie-break by original index
Key Takeaway
🎯 Key Insight: Count feature mentions efficiently with a hash map, then sort by popularity with original index as tie-breaker
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen