All Valid Triplets That Can Represent a Country — LeetCode 1623 Python Solution

EasyLeetCode PremiumDatabase
Problem
#1623
Reading time
4 min

Table schema

SQL
Table: SchoolA +---------------+---------+ | Column Name | Type | +---------------+---------+ | student_id | int | | student_name | varchar | +---------------+---------+ student_id is the column with unique values for this table. Each row of this table contains the name and the id of a student in school A.

Example

SQL
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| student_id    | int     |
| student_name  | varchar |
+---------------+---------+
student_id is the column with unique values for this table.
Each row of this table contains the name and the id of a student in school A.
All student_name are distinct.

Python solution

Python
import duckdb
import pandas as pd

def solution(school_a: pd.DataFrame, school_b: pd.DataFrame, school_c: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("SchoolA", school_a)
    con.register("SchoolB", school_b)
    con.register("SchoolC", school_c)
    return con.execute("""SELECT
    a.student_name AS member_A,
    b.student_name AS member_B,
    c.student_name AS member_C
FROM
    SchoolA AS a,
    SchoolB AS b,
    SchoolC AS c
WHERE
    a.student_name != b.student_name
    AND a.student_name != c.student_name
    AND b.student_name != c.student_name
    AND a.student_id != b.student_id
    AND a.student_id != c.student_id
    AND b.student_id != c.student_id;""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1623. All Valid Triplets That Can Represent a Country?
LeetCode 1623. All Valid Triplets That Can Represent a Country is rated Easy on LeetCode.
What topics does LeetCode 1623. All Valid Triplets That Can Represent a Country cover?
LeetCode 1623. All Valid Triplets That Can Represent a Country is tagged Database on LeetCode.
Is LeetCode 1623. All Valid Triplets That Can Represent a Country a premium problem?
Yes. LeetCode 1623. All Valid Triplets That Can Represent a Country is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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