Problem
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.
Table: Queries
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| year | 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 query.
Write a solution to find the npv
of each query of the Queries
table.
Return the result table in any order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 -
Intuition
For each query (id, year), we need to find the corresponding npv from the NPV table. If not present, return 0. This is a classic left join problem.
Approach
Use a LEFT JOIN from Queries to NPV on (id, year). If npv is NULL, use COALESCE to return 0.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(Q + N)
where Q = number of queries, N = number of NPV rows (due to join). - 🧺 Space complexity:
O(Q)
for result set.