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.
1import java.util.*;
2
This Java solution creates a mapping of sell_date
to a set of products using a HashMap
and Set
. For each activity, the product is added to the corresponding set. After all entries have been processed, the keys (dates) are sorted, and for each date, products are sorted and formatted for output.