Sort Descending
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Given a list of numbers, return a new list sorted in descending order. Do not modify the input.
Biggest first. No exceptions.
Example 1
Input:
nums = [3,1,4,1,5]
Output:
[5,4,3,1,1]
Example 2
Input:
nums = [1]
Output:
[1]
Worked solution and explanation
Why this problem exists in real interviews
Sort a list without mutating the input is a one-liner that tests two specific things: do you know sorted() returns a new list and list.sort() mutates in place, and do you remember the reverse=True flag. Interviewers slip this in to check Python fluency before harder work. The single most common failure is calling nums.sort(reverse=True) and returning None implicitly.
Break down the requirements
Step 1: Use sorted() with reverse=True
sorted(nums, reverse=True) returns a new list in descending order. sorted() is the free function; list.sort() is the in-place method. The spec says 'do not modify the input,' which is the exact distinction between these two APIs.
Step 2: Return the sorted list directly
sorted() returns a list, so return its value. No need for a temporary variable, no need for .copy() (sorted already produces a new object). One expression, one return.
Step 3: Handle empty and single-element lists without special cases
sorted([]) == [] and sorted([1], reverse=True) == [1]. The Timsort implementation handles these in constant time without a branch in your code. Writing 'if not nums: return []' is a tell that you do not trust the standard library.
The solution
def sort_descend(nums):
return sorted(nums, reverse=True)Common follow-up questions
- How would you sort a list of tuples by the second element descending, with ties broken by the first element ascending? (sorted(pairs, key=lambda p: (-p[1], p[0])); or two sorts leveraging stability (sort by primary first, then by secondary, reversed order).)
- What changes if the list is too large to fit in memory? (heapq.nlargest if you only need the top k; otherwise external merge sort or a database with ORDER BY. Mention that Timsort is in-memory only.)
- How would you sort a list of dicts by a key that may be missing? (key=lambda d: d.get('field', default); discuss sentinel values for missing keys (e.g., float('inf') for descending sort of missing-last).)