NPV Queries — LeetCode 1421 Python Solution

EasyLeetCode PremiumDatabase
Problem
#1421
Reading time
2 min

Table schema

SQL
Table: NPV +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | year | int | | npv | int | +---------------+---------+ (id, year) is the primary key (combination of columns with unique values) of this table. The table has information about the id and the year of each inventory and the corresponding net present value.

Example

SQL
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| year          | int     |
| npv           | int     |
+---------------+---------+
(id, year) is the primary key (combination of columns with unique values) of this table.
The table has information about the id and the year of each inventory and the corresponding net present value.

Python solution

Python
import duckdb
import pandas as pd

def solution(npv: pd.DataFrame, queries: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("NPV", npv)
    con.register("Queries", queries)
    return con.execute("""SELECT q.*, IFNULL(npv, 0) AS npv
FROM
    Queries AS q
    LEFT JOIN NPV AS n USING (id, year);""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1421. NPV Queries?
LeetCode 1421. NPV Queries is rated Easy on LeetCode.
What topics does LeetCode 1421. NPV Queries cover?
LeetCode 1421. NPV Queries is tagged Database on LeetCode.
Is LeetCode 1421. NPV Queries a premium problem?
Yes. LeetCode 1421. NPV Queries 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