EasyNo. 0175

Combine Two Tables — LeetCode 175 Python Solution

Topics
Database
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

PythonSolution
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

Related problems
No.ProblemDifficulty
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy
0182Duplicate EmailsEasy

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.

Free to download. Check it runs on your machine, then pick a plan.