Sponsored
Sponsored
This approach employs SQL to directly query the database. We will use GROUP BY to group products by sell_date
. The DISTINCT keyword helps count unique products per date, and the STRING_AGG function (or similar) concatenates product names sorted lexicographically.
Time Complexity: O(n log n), where n is the number of entries. Sorting the products contributes a log factor.
Space Complexity: O(n), for storing products for each date.
1SELECT sell_date, COUNT(DISTINCT product) AS num_sold, STRING_AGG(DISTINCT product ORDER BY product ASC) AS products FROM Activities GROUP BY sell_date ORDER BY sell_date;
The SQL query utilizes GROUP BY
to aggregate rows by sell_date
. COUNT(DISTINCT product)
calculates the number of unique products for each date. STRING_AGG
, a SQL function, concatenates distinct product names sorted alphabetically, resulting in a comma-separated string for the products
column.
This approach involves reading all records into a suitable data structure in a chosen programming language, then processing the data manually. We use dictionaries or hashmaps to group products by date. For each date, extract unique products, sort them, and store the results.
Time Complexity: O(n log n + m log m), where n is the number of records and m is the number of unique products for a specific date due to sorting operations.
Space Complexity: O(n), to store entries in dictionary structures.
1from collections import defaultdict
2
3activities =
The Python solution uses a defaultdict
to group products by sell_date
. We iterate over each record, adding each product to the set corresponding to its date (eliminating duplicates). After grouping, the dates are sorted. For each date, product names are sorted lexicographically, and results are constructed displaying the date, number of unique products, and a comma-separated list of products.