Combine Two Tables — LeetCode 175 Python Solution
EasyDatabase
- Problem
- #175
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
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.