InterviewDB Question

List Sorting: Implement a Custom Multi-Key Sort with Tie-Breaking Rules

Question Details

Problem

You are given a list of employee records. Sort them by: (1) department name ascending, (2) salary descending within the same department, (3) employee name ascending as a final tie-breaker.

python
from dataclasses import dataclass

@dataclass
class Employee:
    name: str
    department: str
    salary: float

def sort_employees(employees: list[Employee]) -> list[Employee]:
    pass

Example:


**input** = [
  Employee("Zara", "Eng", 120000),
  Employee("Alice", "Eng", 120000),
  Employee("Bob", "Eng", 150000),
  Employee("Carol", "Design", 95000),
]
->
  Employee("Carol", "Design", 95000),
  Employee("Bob",   "Eng",    150000),
  Employee("Alice", "Eng",    120000),
  Employee("Zara",  "Eng",    120000),

Follow-ups

  1. How do you sort by salary descending without negating the value -- what key function trick would you use?
  2. What is Python's sort stability guarantee, and how does it help when chaining multiple sort passes?
  3. How would you sort case-insensitively for department names without mutating the original strings?
  4. If the list contains 10 million records, what is the memory and time complexity of Python's Timsort vs. an in-place merge sort?

Full Details

Problem

You are given a list of employee records. Sort them by: (1) department name ascending, (2) salary descending within the same department, (3) employee name ascending as a final tie-breaker.

python
from dataclasses import dataclass

@dataclass
class Employee:
    name: str
    department: str
    salary: float

def sort_employees(employees: list[Employee]) -> list[Employee]:
    pass

Example:


**input** = [
  Employee("Zara", "Eng", 120000),
  Employee("Alice", "Eng", 120000),
  Employee("Bob", "Eng", 150000),
  Employee("Carol", "Design", 95000),
]
->
  Employee("Carol", "Design", 95000),
  Employee("Bob",   "Eng",    150000),
  Employee("Alice", "Eng",    120000),
  Employee("Zara",  "Eng",    120000),

Follow-ups

  1. How do you sort by salary descending without negating the value -- what key function trick would you use?
  2. What is Python's sort stability guarantee, and how does it help when chaining multiple sort passes?
  3. How would you sort case-insensitively for department names without mutating the original strings?
  4. If the list contains 10 million records, what is the memory and time complexity of Python's Timsort vs. an in-place merge sort?
Free preview. Unlock all questions →

Topics

Coding Onsite Phone