Combine Two Tables — LeetCode 175 Python Solution

EasyDatabase
Problem
#175
Reading time
2 min

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

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview