#177

Nth Highest Salary

Medium
DatabaseHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n log n)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a set to track distinct salaries and a min-heap to efficiently find the nth highest salary without sorting all salaries.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a set to collect distinct salaries from the Employee table.
  2. 2Step 2: If the size of the set is less than n, return null.
  3. 3Step 3: Convert the set to a min-heap and pop elements until only n elements remain.
  4. 4Step 4: The root of the heap will be the nth highest salary.
solution.py1 lines
1WITH distinct_salaries AS (SELECT DISTINCT salary FROM Employee) SELECT salary FROM (SELECT salary FROM distinct_salaries ORDER BY salary DESC LIMIT n) AS temp ORDER BY salary ASC LIMIT 1;

Complexity note: Collecting distinct salaries takes O(n) time, and maintaining a heap of size n also takes O(n) time.

  • 1Using distinct salaries is crucial to avoid duplicates affecting the nth highest calculation.
  • 2Min-heaps are efficient for maintaining the top n elements without needing to sort all salaries.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.