#175

Combine Two Tables

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 approach uses a LEFT JOIN operation to efficiently combine the two tables based on the personId. This method leverages the database's ability to handle joins, which is much faster than manually iterating through both tables.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a LEFT JOIN to combine the Person table with the Address table on personId.
  2. 2Step 2: Select the firstName, lastName, city, and state from the combined result.
  3. 3Step 3: Return the result set.
solution.py4 lines
1# Full working Python code
2SELECT p.firstName, p.lastName, a.city, a.state
3FROM Person p
4LEFT JOIN Address a ON p.personId = a.personId;

Complexity note: The time complexity is O(n) because the LEFT JOIN operation processes each row of the Person table once, making it linear in relation to the number of persons.

  • 1Understanding how to use JOIN operations can significantly improve performance when combining data from multiple tables.
  • 2Using LEFT JOIN ensures that we retain all records from the Person table, even if there are no matching records in the Address table.

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