




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
2#include <stdio.h>
3#include <sqlite3.h>
4
5int main() {
6    sqlite3 *db;
7    sqlite3_open("company.db", &db);
8    const char *sql = "SELECT MAX(salary) AS SecondHighestSalary FROM Employee WHERE salary < (SELECT MAX(salary) FROM Employee);";
9    // Execute SQL and handle results
10    sqlite3_close(db);
11    return 0;
12}
13This C solution uses sqlite3 to connect to a database and execute a SQL query that selects the second highest salary from the Employee table. The MAX function is used within a sub-query to find and exclude the highest salary, thereby obtaining the second highest.
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).