easy +8 pts

Keys Sorted by Value Descending

Return dictionary keys in order of decreasing values, with alphabetical tie-breaking.

Write a function `sorted_keys_by_value_desc(d)` that takes a dictionary `d` where keys are strings and values are integers. The function should return a list of the keys sorted by the following criteria: 1. **Primary**: Sort by the associated value in **descending** order (largest value first). 2. **Secondary**: If two keys have the same value, sort those keys **alphabetically in ascending order** (standard Python string order). The returned list must contain all keys exactly once. **Signature:** `def sorted_keys_by_value_desc(d: dict) -> list:`

Constraints

The dictionary may be empty. The dictionary will have at most 10^5 entries. Keys are strings of lowercase English letters; values are integers within the range [-10^9, 10^9]. Your solution should run in O(n log n) time and O(n) space.

Example

>>> sorted_keys_by_value_desc({'a': 2, 'b': 3, 'c': 1})
['b', 'a', 'c']
>>> sorted_keys_by_value_desc({'x': 5, 'y': 5, 'z': 3})
['x', 'y', 'z']
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use the `key` parameter of `sorted()` with a tuple that encodes both the primary (descending value) and secondary (ascending key) criteria.
For the primary criterion, to sort descending, you can use the negative value: `-d[k]`.
Remember that for the secondary criterion, the key itself is used as the tiebreaker in ascending order.
Consider the empty dictionary case: the result should be an empty list.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.