




Sponsored
Sponsored
This approach involves directly querying the database to retrieve the second highest distinct salary. The SQL query utilizes the MAX function in a subquery to exclude the highest salary from consideration, thus efficiently targeting the second highest.
Time Complexity: O(n) - Iterating through database rows
Space Complexity: O(1) - Constant additional space
1
2import sqlite3
3
4conn = sqlite3.connect('company.db')
5cursor = conn.cursor()
6
7query = """
8SELECT MAX(salary) AS SecondHighestSalary FROM Employee 
9WHERE salary < (SELECT MAX(salary) FROM Employee);
10"""
11cursor.execute(query)
12result = cursor.fetchone()[0]
13
14conn.close()
15
16print(result if result is not None else 'None')
17This Python solution uses sqlite3 to execute a SQL query that selects the second highest salary from the Employee table. It uses a sub-query to fetch the maximum salary and exclude it to find the second maximum.
This approach does not rely on SQL but instead employs language-specific paradigms, such as sorting or managing unique salary values in a list or array, to identify the second highest distinct salary.
Time Complexity: O(n log n) - Due to TreeSet insertion
Space Complexity: O(n) - Storage for unique salaries
1
2const sqlite3 = require('sqlite3').verbose
This JavaScript solution uses the sqlite3 library to retrieve salaries from the Employee table. It then utilizes ES6 Set to filter unique salaries and sorts them in descending order. The second element in the array gives us the second highest salary or 'None' if absent.