Similar Problems
Similar Problems not available
Sort Features By Popularity - Leetcode Solution
Companies:
LeetCode: Sort Features By Popularity Leetcode Solution
Difficulty: Medium
Topics: string hash-table sorting array
Problem statement:
Given an array of Feature objects with a name (string) and a popularity score (integer), sort the features in descending order of popularity. If two features have the same popularity score, sort them alphabetically by name.
Example:
Input: features = [Feature(name='abc', score=5), Feature(name='def', score=7), Feature(name='ghi', score=5), Feature(name='jkl', score=3), Feature(name='mno', score=6)]
Output: [Feature(name='def', score=7), Feature(name='mno', score=6), Feature(name='abc', score=5), Feature(name='ghi', score=5), Feature(name='jkl', score=3)]
Solution:
To solve this problem, we can use the built-in sorted() function in Python with a custom key function that first sorts by popularity score in descending order and then by name in alphabetical order if the popularity scores are the same.
Here's the Python code for the solution:
class Feature:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return f"Feature(name='{self.name}', score={self.score})"
def sort_features_by_popularity(features):
return sorted(features, key=lambda f: (-f.score, f.name))
# Example usage
features = [Feature(name='abc', score=5),
Feature(name='def', score=7),
Feature(name='ghi', score=5),
Feature(name='jkl', score=3),
Feature(name='mno', score=6)]
print(sort_features_by_popularity(features))
In the above code, the lambda function passed as the key to sorted() function first sorts by negative popularity score (minus sign for descending order) and then by feature name. The negative score ensures that higher scores come first in the sorting order. Finally, the sorted() function returns the sorted array of features.
Time complexity: O(n log n) - sorting the array takes O(n log n) time.
Space complexity: O(n) - storing the array of feature objects.
Sort Features By Popularity Solution Code
1