Find Nth Highest Distinct Salary
SQL & DataAuto-graded · 20 test casesLast updated
Find the Nth highest unique value in a list of integers, returning None if N is out of valid bounds.
Given a list of integer compensation amounts salaries and a positive 1-indexed target rank n, determine the $n$-th highest distinct compensation amount.
If there are fewer than n distinct values in the input list, or if n is less than 1, return None.
Constraints
- $0 \le \text{len}(salaries) \le 10^5$
- $-10^9 \le salaries[i] \le 10^9$
- $-10^9 \le n \le 10^9$
Examples
Example 1
Input: nth_highest_salary([70000, 90000, 80000], 1)
Output: 90000
Example 2
Input: nth_highest_salary([70000, 90000, 80000], 2)
Output: 80000
Example 3
Input: nth_highest_salary([70000, 90000, 80000], 4)
Output: None
Example 4
Input: nth_highest_salary([100, 200, 200, 300], 2)
Output: 200
Hints
Hint 1
Duplicate values should be collapsed so that ties share the exact same rank level.
Hint 2
Using a set or hash-based collection lets you isolate unique elements before sorting.
Hint 3
Be careful with non-positive values of n and 1-based indexing offsets.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To find the $n$-th highest distinct value from a collection of integers:
- Extract all unique numbers from the input list using a set data structure.
- Sort the unique collection in descending order.
- Check whether $n$ falls within the valid range $[1, k]$, where $k$ is the total count of distinct values.
- If $n$ is valid, return the element at index $n - 1$. Otherwise, return
None.
Correctness
Since identical values share the same rank, collecting unique items first ensures that duplicates do not occupy multiple rank spots (mirroring DENSE_RANK() behavior in SQL). Descending order ensures index 0 corresponds to the 1st highest, index 1 to the 2nd highest, and index n - 1 to the $n$-th highest. Guarding with 1 <= n <= len(distinct) prevents invalid indexing, such as negative bounds or out-of-range offsets.
Complexity
- Time Complexity: $\mathcal{O}(M \log M)$, where $M$ is the number of unique entries in
salaries. Building the set takes $\mathcal{O}(N)$ where $N$ is the total number of salaries, and sorting takes $\mathcal{O}(M \log M)$. - Space Complexity: $\mathcal{O}(M)$ to store the set of distinct elements.
from typing import List, Optional
def nth_highest_salary(salaries: List[int], n: int) -> Optional[int]:
distinct = sorted(set(salaries), reverse=True)
return distinct[n - 1] if 1 <= n <= len(distinct) else None