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
Nth Highest Salary INPUT Employee Table id salary 1 100 2 200 3 300 4 300 5 200 Parameter: N = 2 Find 2nd highest salary ALGORITHM STEPS 1 SELECT DISTINCT Get unique salaries only 2 ORDER BY DESC Sort highest to lowest 3 LIMIT N-1, 1 Skip N-1, take 1 row 4 Handle NULL Return NULL if no result Distinct Sorted: 300 1st 200 2nd 100 3rd SELECT DISTINCT salary ORDER BY salary DESC LIMIT N-1, 1 FINAL RESULT getNthHighestSalary(2) Nth Highest: 200 OK - Found! Edge Case: N=5 Only 3 distinct salaries Returns: NULL Output: {salary: 200} Key Insight: Use DENSE_RANK() or subquery with DISTINCT + OFFSET to handle duplicate salaries efficiently. LIMIT with OFFSET (N-1, 1) skips first N-1 rows and returns exactly the Nth highest value. Wrap in subquery to return NULL when result is empty (fewer than N distinct salaries exist). TutorialsPoint - Nth Highest Salary | Optimal Solution
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