LeetCode 1772: Sort Features by Popularity Solution
Master LeetCode problem 1772 (Sort Features by Popularity), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1772. Sort Features by Popularity
Problem Explanation
Explanation:
To solve this problem, we need to sort the features based on their popularity. The popularity is defined as the total number of requests that contain a particular feature. If two features have the same popularity, they should be ordered lexicographically.
We can achieve this by following these steps:
- Create a map to store the feature as key and its popularity as the value.
- Iterate through the requests and update the popularity of each feature in the map.
- Sort the features based on their popularity. If two features have the same popularity, we sort them lexicographically.
- Return the sorted list of features.
Time Complexity:
The time complexity of this approach is O(n * m * log(m)), where n is the number of requests and m is the average length of a request.
Space Complexity:
The space complexity is O(m*n) for storing the features and their popularity.
:
Solution Code
import java.util.*;
class Solution {
public List<String> sortFeatures(String[] features, String[] responses) {
Map<String, Integer> featurePopularity = new HashMap<>();
for (String response : responses) {
Set<String> seen = new HashSet<>();
for (String feature : features) {
if (response.contains(feature) && !seen.contains(feature)) {
featurePopularity.put(feature, featurePopularity.getOrDefault(feature, 0) + 1);
seen.add(feature);
}
}
}
List<String> sortedFeatures = new ArrayList<>(Arrays.asList(features));
Collections.sort(sortedFeatures, (a, b) -> (featurePopularity.get(b) - featurePopularity.get(a) == 0 ? a.compareTo(b) : featurePopularity.get(b) - featurePopularity.get(a)));
return sortedFeatures;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1772 (Sort Features by Popularity)?
This page provides optimized solutions for LeetCode problem 1772 (Sort Features by Popularity) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1772 (Sort Features by Popularity)?
The time complexity for LeetCode 1772 (Sort Features by Popularity) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1772 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1772 in Java, C++, or Python.