Sponsored
Sponsored
In this approach, the goal is to group the data by both `date_id` and `make_name`. While iterating over the data, for each group, maintain two sets, one for distinct `lead_id`s and one for distinct `partner_id`s. Ensure to keep track of only unique IDs by using sets. Once all data in a group has been processed, the size of each set gives the number of unique IDs.
The time complexity is O(n), where n is the number of entries, as we process each entry once. The space complexity is O(u), where u is the number of unique (date_id, make_name) combinations times the distinct IDs per combination.
1function countDistinctIds(data) {
2 const result = [];
3 const sales = {};
4
5 data.forEach(({ date_id, make_name, lead_id, partner_id }) => {
6 if (!sales[date_id]) {
7 sales[date_id] = {};
8 }
9 if (!sales[date_id][make_name]) {
10 sales[date_id][make_name] = { leads: new Set(), partners: new Set() };
11 }
12 sales[date_id][make_name].leads.add(lead_id);
13 sales[date_id][make_name].partners.add(partner_id);
14 });
15
16 for (const date_id in sales) {
17 for (const make_name in sales[date_id]) {
18 const uniqueLeads = sales[date_id][make_name].leads.size;
19 const uniquePartners = sales[date_id][make_name].partners.size;
20 result.push({
21 date_id: date_id,
22 make_name: make_name,
23 unique_leads: uniqueLeads,
24 unique_partners: uniquePartners
25 });
26 }
27 }
28 return result;
29}
30
31// Example
32const data = [
33 { date_id: '2020-12-8', make_name: 'toyota', lead_id: 0, partner_id: 1 },
34 { date_id: '2020-12-8', make_name: 'toyota', lead_id: 1, partner_id: 0 },
35 // ... other data rows ...
36];
37
38console.log(countDistinctIds(data));This JavaScript solution follows the same logic as the Python solution. The use of ES6 Sets allows us to efficiently manage and count unique entries for `lead_id` and `partner_id`.
SQL can efficiently handle this task using aggregation functions. The plan here is to use the GROUP BY clause with COUNT(DISTINCT ...) to find distinct lead and partner counts for each combination of `date_id` and `make_name`.
The time complexity depends on the database indices and can often be O(n log n) due to sorting and deduplication. The space complexity is determined by the size of the intermediate tables, typically O(g) where g is the size of the distinct groups formed.
1SELECT date_id,
2 make_name,
3 COUNT(DISTINCT lead_id) ASThe SQL approach utilizes the GROUP BY clause to aggregate results based on `date_id` and `make_name`. The COUNT(DISTINCT ...) function is used twice to determine the number of unique `lead_id`s and `partner_id`s within each group. The result is a table with the necessary counts per unique date and make.