Nth Highest Salary - Problem
You're working with a company's Employee database that contains salary information. Your task is to find the nth highest distinct salary from the Employee table.
The Employee table structure:
| Column Name | Type |
|---|---|
| id | int |
| salary | int |
Important points:
idis the primary key with unique values- You need to find distinct salaries (duplicates don't count)
- If there are fewer than
ndistinct salaries, returnnull - The ranking is from highest to lowest (1st highest, 2nd highest, etc.)
Example: If salaries are [100, 200, 300, 200], the distinct salaries in order are [300, 200, 100]. So the 2nd highest distinct salary is 200.
Input & Output
example_1.sql โ Basic Case
$
Input:
Employee table: [{"id": 1, "salary": 100}, {"id": 2, "salary": 200}, {"id": 3, "salary": 300}], n = 2
โบ
Output:
200
๐ก Note:
The distinct salaries in descending order are [300, 200, 100]. The 2nd highest distinct salary is 200.
example_2.sql โ With Duplicates
$
Input:
Employee table: [{"id": 1, "salary": 100}, {"id": 2, "salary": 200}, {"id": 3, "salary": 300}, {"id": 4, "salary": 200}], n = 2
โบ
Output:
200
๐ก Note:
The distinct salaries are [300, 200, 100]. Even though 200 appears twice, it's still the 2nd highest distinct salary.
example_3.sql โ Not Enough Salaries
$
Input:
Employee table: [{"id": 1, "salary": 100}], n = 2
โบ
Output:
null
๐ก Note:
There is only 1 distinct salary (100), but we need the 2nd highest. Since there aren't enough distinct salaries, we return null.
Visualization
Tap to expand
Understanding the Visualization
1
Gather All Scores
Collect all employee salaries from the database table
2
Apply DENSE_RANK()
Assign consecutive ranks to distinct salary values, handling ties appropriately
3
Filter by Position
Find all salaries that have exactly the nth rank
4
Return Result
Return the salary value or null if the position doesn't exist
Key Takeaway
๐ฏ Key Insight: DENSE_RANK() is the perfect tool for finding nth distinct highest values because it automatically handles duplicates while maintaining consecutive ranking, exactly matching our requirement for distinct salary positions.
Time & Space Complexity
Time Complexity
O(n log n)
Database-optimized window function, typically faster than manual sorting
โก Linearithmic
Space Complexity
O(n)
Space for ranking calculation, handled efficiently by database
โก Linearithmic Space
Constraints
- The Employee table contains at least 0 rows
- 1 โค n โค 500
- salary values can be any integer
- Return null if there are fewer than n distinct salaries
- id values are unique (primary key constraint)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code