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 n distinct salaries, return null
  • The parameter n will be passed to your function

Table: Employee

Column NameType
idint
salaryint

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
Finding Nth Highest Distinct SalaryInput: Employeeidsalary1100220033004200DENSE_RANK()ORDER BY DESCRanked Salariessalaryrank300120021003WHERErank = 2Output (N=2)salary200🎯 DENSE_RANK assigns consecutive ranks to distinct valuesDuplicate salaries get same rank, but next distinct salary gets next consecutive rankKey Insight: Handle duplicates correctly while finding nth distinct value
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
Asked in
Amazon 28 Google 22 Microsoft 19 Apple 15
89.0K Views
High Frequency
~18 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen