EasyNo. 0175
Combine Two Tables — LeetCode 175 Python Solution
- Topics
- Database
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Report the first name, last name, city and state of every person on file, keeping people who have no address at all and returning a null city and state for them. Person holds personId (int, primary key), lastName (varchar) and firstName (varchar); Address holds addressId (int, primary key), personId (int, pointing at a person) plus city and state (varchar). The rows may be returned in any order.
Example
- Input
- Person(personId, lastName, firstName) = (1, 'Reyes', 'Carla'), (2, 'Nakamura', 'Dan'), (3, 'Osei', 'Ama'); Address(addressId, personId, city, state) = (1, 2, 'Austin', 'Texas'), (2, 3, 'Denver', 'Colorado')
- Output
- ('Carla', 'Reyes', null, null), ('Dan', 'Nakamura', 'Austin', 'Texas'), ('Ama', 'Osei', 'Denver', 'Colorado')
- Explanation
- Carla has no matching address row, so the left join keeps her with a null city and state.
Python solution
import pandas as pd
def combine_two_tables(person: pd.DataFrame, address: pd.DataFrame) -> pd.DataFrame:
return pd.merge(left=person, right=address, how="left", on="personId")[
["firstName", "lastName", "city", "state"]
]Complexity
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
| 0182 | Duplicate Emails | Easy |
Frequently asked questions
- How hard is LeetCode 175. Combine Two Tables?
LeetCode 175. Combine Two Tables is rated Easy on LeetCode.
- What topics does LeetCode 175. Combine Two Tables cover?
LeetCode 175. Combine Two Tables is tagged Database on LeetCode.