Order Integers Largest to Smallest Keeping Duplicates
Easy · Coding & Algorithms · Data Scientist · Technical Screen
Problem Statement
Write get_descending_ranked(nums) to take a list of integers nums and allocate a separate output list containing every entry of nums arranged from largest value down to smallest value.
Your implementation must satisfy three rules:
- Leave the caller's input list
numsuntouched in memory (allocate and return a distinct list object). - Keep the exact count of every repeated integer so equal values appear side by side in the returned list.
- Return
[]whennumsis empty.
def get_descending_ranked(nums: List[int]) -> List[int]:
Examples
Example 1
Input: nums = [7, -2, 4, 7, 0]
Output: [7, 7, 4, 0, -2]
Explanation: Ordering the five values from highest to lowest places both copies of 7 at the front, followed by 4, 0, and -2, while nums remains [7, -2, 4, 7, 0].
Example 2
Input: nums = [-5, 12, -5, -9, 3]
Output: [12, 3, -5, -5, -9]
Explanation: Positive values 12 and 3 lead, both copies of -5 sit next to one another, and -9 appears last.
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9
Step-by-step walkthrough
Understand the output contract and duplicate rule
We receive
nums, a list of up to100,000integers in[-10^9, 10^9], and must return a newly allocated list ordered from largest to smallest.Two details deserve explicit attention:
- Keep every duplicate grouped together: Any true sort permutes items without discarding any. Once values sit in non-increasing order, equal numbers (such as two
-5s) automatically sit side by side ([12, 3, -5, -5, -9])—duplicates only disappear if you mistakenly convertnumsinto aset. - Never mutate the caller's list: The caller's
numsobject must keep its original element order in memory.
- Keep every duplicate grouped together: Any true sort permutes items without discarding any. Once values sit in non-increasing order, equal numbers (such as two
Why `sorted(nums, reverse=True)` beats `.sort()` and quadratic loops
Python has two standard sorting entry points whose return values differ sharply:
Caller passes: nums = [-5, 12, -5, -9, 3] WRONG: result = nums.sort(reverse=True) nums --> [12, 3, -5, -5, -9] (overwrote caller's list!) result --> None (list.sort() always returns None!) RIGHT: ranked_nums = sorted(nums, reverse=True) nums --> [-5, 12, -5, -9, 3] (caller's list stays intact) ranked_nums --> [12, 3, -5, -5, -9] (separate non-increasing list)Why avoid writing a simple loop that repeatedly scans for
max(nums)or swaps neighboring elements? Atn = 100,000, a quadraticO(n^2)sort executes roughlyn^2 / 2 = 5,000,000,000comparisons, which times out in Python. Python'ssortedruns Timsort (an adaptive hybrid of merge sort and insertion sort) in at mostO(n log n)comparisons—around1.7 * 10^6steps atn = 100,000.Write the solution
Calling
sorted(nums, reverse=True)covers every edge case cleanly:- Empty list
[]-> allocates a fresh[]. - Single element
[-7]-> allocates a fresh[-7]. - Negatives and extremes (
-10^9to10^9) -> Python integers have unbounded precision without overflow, ordering10^9 > 0 > -1 > -10^9directly.
def get_descending_ranked(nums: List[int]) -> List[int]: # `sorted(...)` allocates a brand-new list so the caller's `nums` is never mutated # (unlike `nums.sort()`, which mutates in place and returns `None`). # `reverse=True` orders values from largest to smallest while keeping all duplicates # grouped together (e.g., [7, -2, 4, 7, 0] -> [7, 7, 4, 0, -2]) and returns [] for []. ranked_nums = sorted(nums, reverse=True) return ranked_nums- Empty list
How to answer if built-in sorting is off-limits: descending merge sort
If an interviewer asks you to write the sort from scratch without
sorted, avoidO(n^2)swaps and write merge sort—a divide-and-conquer routine that guaranteesO(n log n)time:- Base case: A list of length
0or1is already ordered; return a shallow copylist(nums). - Divide: Split
numsatmid = len(nums) // 2and recursively sort each half from largest to smallest. - Merge: Advance two indices
iandjacross the sorted halves, appending whichever front element is larger (left[i] >= right[j]) until both halves (and all duplicates) are exhausted.
Input: [7, -2, 4, 7, 0] Split: [7, -2] [4, 7, 0] Sort halves: [7, -2] [7, 4, 0] Merge two pointers (pick larger front value at each step): compare 7 vs 7 -> take 7 -> [7] compare -2 vs 7 -> take 7 -> [7, 7] compare -2 vs 4 -> take 4 -> [7, 7, 4] compare -2 vs 0 -> take 0 -> [7, 7, 4, 0] leftover left -> take -2 -> [7, 7, 4, 0, -2]Lead with
sorted(nums, reverse=True)unless asked to build a custom sort; complete merge-sort code appears in the explanation under Alternative approaches.- Base case: A list of length
Trace both examples step by step
Example 1: nums = [7, -2, 4, 7, 0] Non-incr. = 7 >= 7 >= 4 >= 0 >= -2 (both 7s kept side by side) ranked_nums = [7, 7, 4, 0, -2] (nums remains [7, -2, 4, 7, 0]) Example 2: nums = [-5, 12, -5, -9, 3] Non-incr. = 12 >= 3 >= -5 >= -5 >= -9 (both -5s kept side by side) ranked_nums = [12, 3, -5, -5, -9] (nums remains [-5, 12, -5, -9, 3])Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def get_descending_ranked(nums: List[int]) -> List[int]: # `sorted(...)` allocates a brand-new list so the caller's `nums` is never mutated # (unlike `nums.sort()`, which mutates in place and returns `None`). # `reverse=True` orders values from largest to smallest while keeping all duplicates # grouped together (e.g., [7, -2, 4, 7, 0] -> [7, 7, 4, 0, -2]) and returns [] for []. ranked_nums = sorted(nums, reverse=True) return ranked_nums✅ Submit now — all tests should pass.
Intuition & how it works
Imagine photocopying a stack of scorecards and stacking the fresh copies with the highest score on top and the lowest score at the bottom, leaving the original pile in its exact arrival order. Whenever two cards share the same number—such as two -5s—both copies stay right next to each other in the sorted stack.
A naive loop that repeatedly scans for max(nums) and deletes it (selection sort) or swaps adjacent out-of-order pairs (bubble sort) rescans the list up to n times, taking O(n^2) steps—roughly 5 billion operations when n = 100,000, which times out in Python. Two classic Python mistakes are calling nums.sort(reverse=True), an in-place sort (a method that mutates the caller's list directly and returns None), or wrapping nums in set(...), which discards repeated values. Calling sorted(nums, reverse=True) builds a brand-new list in O(n log n) worst-case time via Python's Timsort (an adaptive hybrid of merge sort and insertion sort).
Walk through Example 2 with nums = [-5, 12, -5, -9, 3]:
sorted(nums, reverse=True)copies the5integer references into a new listranked_nums.- Timsort arranges values from largest to smallest:
12, then3, then both-5s side by side, and-9last. - The function returns
[12, 3, -5, -5, -9], while the caller'snumsstays[-5, 12, -5, -9, 3].
Complexity
- Time:
O(n log n)worst-case and average-case comparisons forn = len(nums), because Timsort merges ordered runs across at mostlog2(n)levels (~1.7 * 10^6operations atn = 10^5). On inputs that are already monotonic ascending or descending, Timsort spots the single run in one pass and finishes inO(n)time. - Space:
O(n)becausesortedallocates a newn-element output list (plus Timsort's temporary merge buffer of at mostn // 2references).
Edge cases
- Empty list (
nums = []):sorted([], reverse=True)returns a fresh empty list[]with no extra branches. - Single-element list (
nums = [-7]): Returns a distinct list[-7]rather than aliasingnums. - All equal values (
[4, 4, 4, 4]): Keeps all four copies ([4, 4, 4, 4]) inO(n)comparisons. - Negative values and
±10^9bounds: Arbitrary-precision Python integers compare directly without 32-bit overflow, placing10^9ahead of0,-1, and-10^9. - Input immutability:
sorted(nums, reverse=True)guaranteesgot is not numsand leavesnumsuntouched even whennumswas already sorted.
Common mistakes
- Returning
nums.sort(reverse=True):list.sort()mutatesnumsin place and returnsNone, breaking both the return type and caller immutability. - Returning
sorted(nums).reverse():list.reverse()also mutates in place and returnsNone, discarding the sorted list. - Passing
numsthroughset(nums): Sets strip duplicate entries ([-5, 12, -5, -9, 3]shrinks to[12, 3, -5, -9]), violating multiplicity preservation. - Writing an
O(n^2)loop atn = 10^5: Repeatedmax+removeor nested swap loops time out on100,000integers. - Allocating a counting-sort array over
[-10^9, 10^9]: Creating2 * 10^9 + 1buckets exhausts gigabytes of memory even on tiny inputs.
Alternative approaches
Custom descending merge sort (when built-in sorting is disallowed). Merge sort is a divide-and-conquer algorithm that splits the list into halves, recursively sorts each half, and merges the two halves in O(n) work per level across log2(n) levels, guaranteeing O(n log n) time and O(n) space on every input:
def merge_sort_descending(nums: list[int]) -> list[int]:
if len(nums) <= 1:
return list(nums) # copy so a 1-element input is never aliased
mid = len(nums) // 2
left = merge_sort_descending(nums[:mid])
right = merge_sort_descending(nums[mid:])
merged: list[int] = []
i = 0
j = 0
while i < len(left) and j < len(right):
# Choosing `left[i]` on ties (`>=`) preserves stability.
if left[i] >= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
Choosing left[i] whenever left[i] == right[j] makes this a stable sort (preserving the original left-to-right order of equal items). At n = 10^5, recursion depth reaches only ceil(log2(10^5)) = 17 frames.
Follow-up questions
- What is the asymptotic runtime of your implementation, and why does Python's built-in sorting routine achieve that bound?
sorted(nums, reverse=True)runs inO(n log n)worst-case time andO(n)best-case time. Under the hood, Timsort is a comparison sort (ordering elements solely via pairwise<or>tests): it identifies naturally ordered runs, extends short runs with binary insertion sort, and merges balanced runs acrossO(log n)levels doingO(n)work per level. By information theory, distinguishing alln!possible permutations using two-outcome comparisons requires at leastlog2(n!) ≈ n log2(n)comparisons in the worst case, soO(n log n)is optimal among comparison sorts. - How would you adapt the function if duplicate values had to be removed so each distinct integer appeared once from largest to smallest? Deduplicate with a hash set first and sort only the unique integers:
return sorted(set(nums), reverse=True). Constructingset(nums)takesO(n)average time, and sorting theuunique entries takesO(u log u)time, which is noticeably faster thanO(n log n)when duplicates are common. If hashing were restricted, you would sort allnnumbers inO(n log n)time and append each value during a singleO(n)sweep whenever it differs from the previously appended value. - If the dataset lived on disk and exceeded available RAM, how would you sort all integers from highest to lowest? Apply external merge sort (a disk-streaming divide-and-conquer sort built for out-of-core datasets). First, read the input stream in RAM-sized blocks (say
500 MBper block), sort each block descending in memory, and flush each sorted block to a temporary run file on disk. Second, run ak-way merge across all run files using a priority queue holding only the current front integer of each buffered file stream (heapq.merge(*runs, reverse=True)in Python), writing the globally ordered stream to disk inO(k)RAM; if thousands of runs exist, merge them in multi-stage batches to stay within OS open-file limits.
Follow-up questions
- What is the asymptotic runtime of your implementation, and why does Python's built-in sorting routine achieve that bound?
- How would you adapt the function if duplicate values had to be removed so each distinct integer appeared once from largest to smallest?
- If the dataset lived on disk and exceeded available RAM, how would you sort all integers from highest to lowest?
Similar questions
- Two-Stage Recommendation System for Cold-Start Content Feeds
- A/B Test Sample Size and Runtime
- Aligning Ambiguous Product Goals and Triaging a Sudden DAU Drop
- Shipping Decisions After an Inconclusive A/B Test
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger