Rank Top Earners Worldwide After Converting to USD
Heaps, Sorting & SearchAuto-graded · 17 test casesLast updated
Merge several lists of employee records, convert each salary to USD using a rate map, and return the top N earners with a deterministic tie-break.
A company keeps employee records in several separate files, one per country or region. Each file is a list of dictionaries. You must combine them and find the highest earners worldwide, with all pay expressed in US dollars.
Write a function that receives:
staff_files: a list of lists of dictionaries. Each dictionary is one employee and has the keysemp_id(int),name(str) andsalary(number, in the employee's local currency). It also carries a currency indicator, described below.fx_rates: a dictionary mapping a currency code to its USD rate, that is, how many US dollars one unit of that currency is worth.top_n: how many employees to return (default10).
Determining an employee's currency
For each employee, the currency code used to look up the rate is chosen like this:
- If the record has a
"currency"key, use its value. - Otherwise, if the record has a
"country"key, use its value as the code. - Otherwise, assume the code is
"USD".
Task
- Concatenate all the files into one collection of employees. Every record from every file is kept, including records that look identical.
- For each employee, look up the rate for their currency code in
fx_rates. If the code is not infx_rates, the employee is skipped and does not appear in the result. - Compute the USD salary as
salary * rate, with the multiplication done in that order and with no rounding. - Sort the employees by USD salary from highest to lowest. If two employees have equal USD salaries, the one with the smaller
emp_idcomes first. - Return the first
top_nentries. Iftop_nis zero or negative, return an empty list. If fewer thantop_nemployees qualify, return all of them.
Output format
Return a list of dictionaries, in ranked order, each with exactly these keys:
emp_id: the employee's idname: the employee's namesalary_usd: the converted salary, computed assalary * rate
Constraints
- The number of files and the number of employees per file may be zero.
emp_idvalues are integers; they may repeat across files.- Salaries and rates are non-negative numbers.
- Do not round
salary_usd; return the raw product. - Do not modify the input data.
Examples
Example 1
Input: rank_top_earners_usd([[{'emp_id': 1, 'name': 'Alice', 'salary': 120000, 'country': 'USD'}, {'emp_id': 2, 'name': 'Bob', 'salary': 95000, 'country': 'USD'}, {'emp_id': 3, 'name': 'Carol', 'salary': 115000, 'country': 'USD'}], [{'emp_id': 4, 'name': 'David', 'salary': 100000, 'currency': 'EUR'}, {'emp_id': 5, 'name': 'Eri', 'salary': 20000000, 'currency': 'JPY'}]], {'USD': 1, 'EUR': 1.12, 'JPY': 0.0091}, 10)
Output: [{'emp_id': 5, 'name': 'Eri', 'salary_usd': 182000}, {'emp_id': 1, 'name': 'Alice', 'salary_usd': 120000}, {'emp_id': 3, 'name': 'Carol', 'salary_usd': 115000}, {'emp_id': 4, 'name': 'David', 'salary_usd': 112000.00000000001}, {'emp_id': 2, 'name': 'Bob', 'salary_usd': 95000}]
Hints
Hint 1
Start by flattening all the files into one list. A currency can be resolved per record with a dictionary lookup that falls back to another key and then to a default.
Hint 2
Skip any record whose currency code has no entry in the rate map before you build the converted entries.
Hint 3
Sort with a composite key: negative USD salary first, then emp_id ascending. Finally slice with max(0, top_n) so that a negative limit gives an empty list.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a short pipeline: merge, convert, rank.
- Merge. Walk through every file and put all the records into one flat list. Nothing is deduplicated, so every record is kept.
- Convert. For each record, pick the currency code: the
currencyfield if it exists, otherwisecountry, otherwise"USD". Look the code up infx_rates. If there is no rate, skip the employee. Otherwise build a small result dictionary holdingemp_id,nameandsalary * rate. - Rank. Sort by
(-salary_usd, emp_id). Negating the salary gives descending pay, andemp_idascending breaks ties deterministically. Slice the firstmax(0, top_n)entries, so a zero or negative limit produces an empty list.
Why it is correct
- Flattening visits every record exactly once, so no employee is lost or duplicated.
- The fallback chain for the currency code follows the stated rules, and skipping unknown codes matches the "skip" rule.
- Using
salary * ratewithout rounding keeps the values and the comparison exact, so near-ties are not merged. - The sort key totally orders the entries (pay first, then
emp_id), so the output is deterministic. Taking a prefix of the sorted list gives exactly the top entries.
Complexity
Let N be the total number of employees.
- Time: O(N log N) for the full sort. A heap-based selection could reduce this to O(N log k), but the plain sort is simpler and sufficient.
- Space: O(N) for the merged and converted lists.
Reference solution
from typing import List, Dict
def rank_top_earners_usd(staff_files: List[List[Dict]], fx_rates: Dict[str, float], top_n: int = 10) -> List[Dict]:
everyone = []
for file in staff_files:
everyone.extend(file)
converted = []
for emp in everyone:
code = emp.get('currency', emp.get('country', 'USD'))
rate = fx_rates.get(code)
if rate is None:
continue
converted.append({
'emp_id': emp['emp_id'],
'name': emp['name'],
'salary_usd': emp['salary'] * rate,
})
converted.sort(key=lambda e: (-e['salary_usd'], e['emp_id']))
return converted[:max(0, top_n)]