Difficulty: Easy | Acceptance: 88.70% | Paid: No Topics: Database
Table: Products
+-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | low_fats | enum | | recyclable | enum | +-------------+---------+ product_id is the primary key (column with unique values) for this table. low_fats is an ENUM (category) of type (‘Y’, ‘N’) where ‘Y’ means it is low fat and ‘N’ means it is not low fat. recyclable is an ENUM (category) of types (‘Y’, ‘N’) where ‘Y’ means the product is recyclable and ‘N’ means it is not recyclable.
Write a solution to find the ids of products that are both low fat and recyclable.
Return the result table in any order.
The result format is in the following example.
- Examples
- Constraints
- Basic WHERE with AND
- Using Boolean Logic
Examples
Example 1
Input:
Products table:
+-------------+----------+------------+
| product_id | low_fats | recyclable |
+-------------+----------+------------+
| 0 | Y | N |
| 1 | Y | Y |
| 2 | N | Y |
| 3 | Y | Y |
| 4 | N | N |
+-------------+----------+------------+
Output:
+-------------+
| product_id |
+-------------+
| 1 |
| 3 |
+-------------+
Explanation: Only products 1 and 3 are both low fat and recyclable.
Constraints
1 <= product_id <= 1000
Basic WHERE with AND
Intuition Use a simple WHERE clause with AND to filter rows where both conditions are true.
Steps
- Select product_id from Products table
- Filter where low_fats = ‘Y’ AND recyclable = ‘Y’
import pandas as pd
def find_products(products: pd.DataFrame) -> pd.DataFrame:
result = products[(products['low_fats'] == 'Y') & (products['recyclable'] == 'Y')]
return result[['product_id']]Complexity
- Time: O(n) where n is the number of rows in Products table
- Space: O(k) where k is the number of matching products
- Notes: This is the most straightforward and efficient approach for this problem.
Using Boolean Logic
Intuition Use boolean logic to combine conditions and filter the results.
Steps
- Select product_id from Products table
- Apply boolean AND operation on both conditions
import pandas as pd
def find_products(products: pd.DataFrame) -> pd.DataFrame:
mask = (products['low_fats'] == 'Y') & (products['recyclable'] == 'Y')
result = products.loc[mask, ['product_id']]
return resultComplexity
- Time: O(n) where n is the number of rows in Products table
- Space: O(k) where k is the number of matching products
- Notes: This approach demonstrates explicit boolean logic and iteration.