




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
2import java.sql.Connection;
3
This Java solution uses JDBC to connect to the SQLite database, retrieves all salaries, and uses a TreeSet to store unique salaries in descending order. The second highest salary, if available, is then retrieved by skipping the first element (highest).