Problem
Table: Sales
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| sale_id | int |
| product_name | varchar |
| sale_date | date |
+--------------+---------+
sale_id is the column with unique values for this table.
Each row of this table contains the product name and the date it was sold.
Since table Sales was filled manually in the year 2000
, product_name
may contain leading and/or trailing white spaces, also they are case-insensitive.
Write a solution to report
product_name
in lowercase without leading or trailing white spaces.sale_date
in the format('YYYY-MM')
.total
the number of times the product was sold in this month.
Return the result table ordered by product_name
in ascending order. In case of a tie, order it by sale_date
in ascending order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – String Trimming and Lowercase
Intuition
We want to remove leading/trailing spaces and convert product names to lowercase for consistency. This is a classic string cleaning problem, solved with SQL string functions or pandas string methods.
Approach
- Use TRIM to remove leading/trailing spaces from product_name.
- Use LOWER to convert product_name to lowercase.
- Return the cleaned product_name for each sale_id, along with the original name.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N*L)
, where N is the number of rows and L is the average length of product_name, since we process each name. - 🧺 Space complexity:
O(N*L)
, for storing the cleaned names.