Nth Highest Salary - Problem
Given the Employee table, write a solution to find the nth highest distinct salary.
Key requirements:
- Find the
nth highest distinct salary (duplicates are treated as one value) - If there are fewer than
ndistinct salaries, returnnull - The parameter
nwill be passed to your function
Table: Employee
| Column Name | Type |
|---|---|
| id | int |
| salary | int |
id is the primary key for this table. Each row contains information about the salary of an employee.
Table Schema
Employee
| Column Name | Type | Description |
|---|---|---|
id
PK
|
int | Primary key, unique employee identifier |
salary
|
int | Employee salary amount |
Primary Key: id
Note: Each row represents one employee with their salary
Input & Output
Example 1 — Finding 2nd Highest Salary
Input Table:
| id | salary |
|---|---|
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
Output:
| getNthHighestSalary(2) |
|---|
| 200 |
💡 Note:
For n = 2, we need the 2nd highest distinct salary. The distinct salaries in descending order are: 300, 200, 100. The 2nd highest is 200.
Example 2 — With Duplicate Salaries
Input Table:
| id | salary |
|---|---|
| 1 | 100 |
| 2 | 200 |
| 3 | 200 |
Output:
| getNthHighestSalary(2) |
|---|
| 100 |
💡 Note:
For n = 2 with duplicate salaries. Distinct salaries in descending order are: 200, 100. The 2nd highest distinct salary is 100.
Example 3 — Insufficient Distinct Salaries
Input Table:
| id | salary |
|---|---|
| 1 | 100 |
Output:
| getNthHighestSalary(2) |
|---|
💡 Note:
For n = 2 but only 1 distinct salary exists. Since there are fewer than 2 distinct salaries, the function returns null (empty result).
Constraints
-
1 ≤ Employee.id ≤ 1000 -
-10^6 ≤ salary ≤ 10^6 -
1 ≤ n ≤ 1000 - All salary values are integers
Visualization
Tap to expand
Understanding the Visualization
1
Input
Employee table with salaries
2
Rank
Rank distinct salaries descending
3
Filter
Select salary with rank = n
Key Takeaway
🎯 Key Insight: Use DENSE_RANK() for nth highest problems to handle duplicate values correctly
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code