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 nums untouched 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 [] when nums is 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

  1. Understand the output contract and duplicate rule

    We receive nums, a list of up to 100,000 integers in [-10^9, 10^9], and must return a newly allocated list ordered from largest to smallest.

    Two details deserve explicit attention:

    1. 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 convert nums into a set.
    2. Never mutate the caller's list: The caller's nums object must keep its original element order in memory.
  2. 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? At n = 100,000, a quadratic O(n^2) sort executes roughly n^2 / 2 = 5,000,000,000 comparisons, which times out in Python. Python's sorted runs Timsort (an adaptive hybrid of merge sort and insertion sort) in at most O(n log n) comparisons—around 1.7 * 10^6 steps at n = 100,000.

  3. 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^9 to 10^9) -> Python integers have unbounded precision without overflow, ordering 10^9 > 0 > -1 > -10^9 directly.
    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
    
  4. 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, avoid O(n^2) swaps and write merge sort—a divide-and-conquer routine that guarantees O(n log n) time:

    1. Base case: A list of length 0 or 1 is already ordered; return a shallow copy list(nums).
    2. Divide: Split nums at mid = len(nums) // 2 and recursively sort each half from largest to smallest.
    3. Merge: Advance two indices i and j across 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.

  5. 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])
    
  6. 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]:

  1. sorted(nums, reverse=True) copies the 5 integer references into a new list ranked_nums.
  2. Timsort arranges values from largest to smallest: 12, then 3, then both -5s side by side, and -9 last.
  3. The function returns [12, 3, -5, -5, -9], while the caller's nums stays [-5, 12, -5, -9, 3].

Complexity

  • Time: O(n log n) worst-case and average-case comparisons for n = len(nums), because Timsort merges ordered runs across at most log2(n) levels (~1.7 * 10^6 operations at n = 10^5). On inputs that are already monotonic ascending or descending, Timsort spots the single run in one pass and finishes in O(n) time.
  • Space: O(n) because sorted allocates a new n-element output list (plus Timsort's temporary merge buffer of at most n // 2 references).

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 aliasing nums.
  • All equal values ([4, 4, 4, 4]): Keeps all four copies ([4, 4, 4, 4]) in O(n) comparisons.
  • Negative values and ±10^9 bounds: Arbitrary-precision Python integers compare directly without 32-bit overflow, placing 10^9 ahead of 0, -1, and -10^9.
  • Input immutability: sorted(nums, reverse=True) guarantees got is not nums and leaves nums untouched even when nums was already sorted.

Common mistakes

  • Returning nums.sort(reverse=True): list.sort() mutates nums in place and returns None, breaking both the return type and caller immutability.
  • Returning sorted(nums).reverse(): list.reverse() also mutates in place and returns None, discarding the sorted list.
  • Passing nums through set(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 at n = 10^5: Repeated max + remove or nested swap loops time out on 100,000 integers.
  • Allocating a counting-sort array over [-10^9, 10^9]: Creating 2 * 10^9 + 1 buckets 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 in O(n log n) worst-case time and O(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 across O(log n) levels doing O(n) work per level. By information theory, distinguishing all n! possible permutations using two-outcome comparisons requires at least log2(n!) ≈ n log2(n) comparisons in the worst case, so O(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). Constructing set(nums) takes O(n) average time, and sorting the u unique entries takes O(u log u) time, which is noticeably faster than O(n log n) when duplicates are common. If hashing were restricted, you would sort all n numbers in O(n log n) time and append each value during a single O(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 MB per block), sort each block descending in memory, and flush each sorted block to a temporary run file on disk. Second, run a k-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 in O(k) RAM; if thousands of runs exist, merge them in multi-stage batches to stay within OS open-file limits.

Follow-up questions

Similar questions

More Yelp interview questions

All 5 Yelp questions →