Problem
Table: Customers
+--------------+------+
| Column Name | Type |
+--------------+------+
| customer_id | int |
| year | int |
| revenue | int |
+--------------+------+
(customer_id, year) is the primary key (combination of columns with unique values) for this table.
This table contains the customer ID and the revenue of customers in different years.
Note that this revenue can be negative.
Write a solution to report the customers with postive revenue in the year 2021.
Return the result table in any order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – Simple Filtering
Intuition
We need to select customers who have positive revenue in the year 2021. This is a straightforward filtering problem.
Approach
- For MySQL/PostgreSQL:
- Select rows where
year = 2021
andrevenue > 0
. - Return the
customer_id
column.
- Select rows where
- For Python (Pandas):
- Filter the DataFrame for rows where
year == 2021
andrevenue > 0
. - Return the
customer_id
column as a DataFrame.
- Filter the DataFrame for rows where
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, as we scan all rows once. - 🧺 Space complexity:
O(n)
, for storing the filtered results.