#1378

Replace Employee ID With The Unique Identifier

Easy
DatabaseHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution uses a HashMap to store the unique IDs for quick lookups. This significantly reduces the time complexity by allowing us to find unique IDs in constant time.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a HashMap to store the unique_id for each id from the EmployeeUNI table.
  2. 2Step 2: Populate the HashMap with entries from EmployeeUNI.
  3. 3Step 3: Select the name from Employees and look up the unique_id in the HashMap.
  4. 4Step 4: If the id is not found in the HashMap, return null for unique_id.
  5. 5Step 5: Return the results.
solution.py4 lines
1# Full working Python code
2SELECT COALESCE(eu.unique_id, null) AS unique_id, e.name
3FROM Employees e
4LEFT JOIN EmployeeUNI eu ON e.id = eu.id;

Complexity note: The time complexity is O(n) because we are iterating through the EmployeeUNI table once to create the HashMap, and then we perform a single pass through the Employees table.

  • 1Using a HashMap allows for O(1) lookups, significantly speeding up the process.
  • 2LEFT JOIN in SQL is a powerful tool for combining data from two tables based on a common key.

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