Leetcode #1501: Countries You Can Safely Invest In
In this guide, we solve Leetcode #1501 Countries You Can Safely Invest In in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Table Person: +----------------+---------+ | Column Name | Type | +----------------+---------+ | id | int | | name | varchar | | phone_number | varchar | +----------------+---------+ id is the column of unique values for this table. Each row of this table contains the name of a person and their phone number.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Database
Intuition
The task is relational in nature, which maps cleanly to DataFrame operations in Python.
By treating tables as DataFrames, joins and group-bys become concise and readable.
Approach
Load the inputs as DataFrames and apply the appropriate merge, filter, or group-by.
Select or rename the columns to match the required output.
Steps:
- Load inputs as DataFrames.
- Apply merge/groupby/filter operations.
- Select the output columns.
Example
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| id | int |
| name | varchar |
| phone_number | varchar |
+----------------+---------+
id is the column of unique values for this table.
Each row of this table contains the name of a person and their phone number.
Phone number will be in the form 'xxx-yyyyyyy' where xxx is the country code (3 characters) and yyyyyyy is the phone number (7 characters) where x and y are digits. Both can contain leading zeros.
Python Solution
import duckdb
import pandas as pd
# Pass input tables as keyword arguments matching the SQL table names.
def solution(**tables) -> pd.DataFrame:
con = duckdb.connect()
for name, df in tables.items():
con.register(name, df)
return con.execute("""SELECT country
FROM
(
SELECT c.name AS country, AVG(duration) AS duration
FROM
Person
JOIN Calls ON id IN(caller_id, callee_id)
JOIN Country AS c ON LEFT(phone_number, 3) = country_code
GROUP BY 1
) AS t
WHERE duration > (SELECT AVG(duration) FROM Calls);""").df()
Complexity
The time complexity is O(n log n) (typical). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.