Collapse Rapid Cart Adds into Daily Pacific Action Counts
Arrays & HashingAuto-graded · 15 test casesLast updated
Filter add-to-cart events, convert UTC to Pacific dates, merge rapid repeats into single actions with a chained gap rule, and count the actions per user, date and SKU.
Collapse Rapid Cart Adds into Daily Pacific Action Counts
You are given a raw clickstream log as a list of event dictionaries. Some events are repeated taps on the same "add to cart" button. Your job is to merge those bursts into single logical actions and report how many actions each user took per product per Pacific calendar day.
Input
event_log is a list of dictionaries. Each dictionary has these keys:
user_id: identifier of the user (int or string).event_time_utc: an ISO-8601 timestamp string, such as"2025-08-30 16:00:00". A string with no offset is in UTC. A string ending inZor carrying an explicit offset must be converted to the correct instant.event_type: string, such as"add_to_cart"or"purchase_click".session_id: session identifier (may be missing orNone).props_json: extra properties, given either as a dictionary or as a JSON-encoded string of a dictionary. It may also beNoneor empty. The product code is under the key"sku". If the key is absent, the SKU isNone.
Task
- Ignore every event whose
event_typeis not"add_to_cart". - For each remaining event, read its
skuand compute its local date: the calendar date ofevent_time_utcin theAmerica/Los_Angelestime zone, formattedYYYY-MM-DD. Daylight saving time must be handled correctly. Convert the instant. Do not just relabel the clock time. - Group the events by
(user_id, session_id, sku)and sort each group by time. Within a group, an event starts a new action if it is the first event in the group, or if its gap to the immediately preceding event in that group is strictly greater than 2 minutes. Otherwise it belongs to the same action as the previous event.- The rule chains: events at 0:00, 1:30 and 3:00 are all one action.
- A gap of exactly 2 minutes still belongs to the same action.
- Each action is attributed to the local date of the event that starts it.
- Count actions per
(user_id, local_date, sku). Counts from different sessions are added together.
Output
Return a list of dictionaries, each with exactly these keys:
user_idlocal_dt: the Pacific date string.skudedup_add_to_cart_cnt: the number of actions (an integer, at least 1).
Include only combinations that have at least one action. Sort the list by str(user_id), then local_dt, then str(sku), all ascending. If there are no add-to-cart events, return an empty list.
Constraints
0 <= len(event_log) <= 10^5- Timestamps are valid ISO-8601 strings. Naive ones are UTC.
- Gaps are measured on the real time line, not on local clock times.
props_jsonis either a dict, a JSON string of a dict, orNone.- Events may arrive in any order.
Examples
Example 1
Input: summarize_cart_actions([{'user_id': 1, 'event_time_utc': '2025-08-30 16:00:00', 'event_type': 'add_to_cart', 'session_id': 's1', 'props_json': {'sku': 'A1', 'qty': 1}}, {'user_id': 1, 'event_time_utc': '2025-08-30 16:01:00', 'event_type': 'add_to_cart', 'session_id': 's1', 'props_json': {'sku': 'A1', 'qty': 1}}, {'user_id': 1, 'event_time_utc': '2025-08-30 16:05:00', 'event_type': 'purchase_click', 'session_id': 's1', 'props_json': {}}, {'user_id': 2, 'event_time_utc': '2025-09-01 01:02:03', 'event_type': 'add_to_cart', 'session_id': 's2', 'props_json': {'sku': 'B2', 'qty': 2}}, {'user_id': 3, 'event_time_utc': '2025-08-25 09:10:00', 'event_type': 'add_to_cart', 'session_id': 's3', 'props_json': {'sku': 'C3', 'qty': 1}}])
Output: [{'user_id': 1, 'local_dt': '2025-08-30', 'sku': 'A1', 'dedup_add_to_cart_cnt': 1}, {'user_id': 2, 'local_dt': '2025-08-31', 'sku': 'B2', 'dedup_add_to_cart_cnt': 1}, {'user_id': 3, 'local_dt': '2025-08-25', 'sku': 'C3', 'dedup_add_to_cart_cnt': 1}]
Hints
Hint 1
Filter first, then build a dictionary that maps (user_id, session_id, sku) to a list of (timestamp, local_date) pairs.
Hint 2
Sort each list by timestamp and compare every event only with the one right before it. Start a new action when there is no predecessor or the gap is strictly greater than 2 minutes. Update the 'previous' time after every event, even duplicates, so chains work.
Hint 3
Use zoneinfo to convert the aware UTC instant to America/Los_Angeles before taking .date(). Then tally actions in a second dictionary keyed by (user_id, local_date, sku) and sort the output by the string forms of user_id and sku.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Filter and normalize. Keep only
add_to_cartevents. Parseprops_json(decode it if it is a string, treatNoneas empty) to get thesku. Parse the timestamp, treat naive values as UTC, and convert the instant toAmerica/Los_Angeleswithzoneinfoto get the local date string. - Group. Put each event's
(timestamp, local_date)into a bucket keyed by(user_id, session_id, sku). - Detect actions. Sort each bucket by timestamp. Walk it while remembering the previous event's timestamp. An event starts a new action if there is no previous event or the gap is strictly greater than 2 minutes. The previous timestamp is updated after every event, which makes the rule chain.
- Count. Each new action adds 1 to a counter keyed by
(user_id, local_date, sku), using the date of the starting event. This sums across sessions automatically. - Format. Convert the counter to a list of dicts and sort by
str(user_id),local_dt,str(sku).
Why it is correct
- Timezone conversion is applied to the actual instant, so DST shifts (PDT vs PST) are handled. Gaps are computed on aware datetimes, so a fall-back hour cannot create negative or duplicated gaps.
- Comparing each event to its immediate predecessor, rather than to the start of the action, implements the chained-gap rule. An exact 2-minute gap does not exceed the threshold, so it merges.
- Grouping by session and SKU means bursts are only merged within the same session and product, while the final tally merges sessions on the same day.
Complexity
With n add-to-cart events, sorting dominates: O(n log n) time and O(n) space.
Reference solution
import json
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from typing import Dict, List
def summarize_cart_actions(event_log: List[Dict]) -> List[Dict]:
pacific = ZoneInfo("America/Los_Angeles")
groups = {}
for event in event_log:
if event.get("event_type") != "add_to_cart":
continue
props = event.get("props_json")
if isinstance(props, str):
props = json.loads(props)
props = props or {}
sku = props.get("sku")
ts = datetime.fromisoformat(
event["event_time_utc"].replace("Z", "+00:00")
)
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
local_dt = ts.astimezone(pacific).date().isoformat()
key = (event["user_id"], event.get("session_id"), sku)
groups.setdefault(key, []).append((ts, local_dt))
counts = {}
max_gap = timedelta(minutes=2)
for (user_id, _session, sku), rows in groups.items():
rows.sort(key=lambda r: r[0])
prev = None
for ts, local_dt in rows:
if prev is None or ts - prev > max_gap:
k = (user_id, local_dt, sku)
counts[k] = counts.get(k, 0) + 1
prev = ts
result = [
{"user_id": u, "local_dt": d, "sku": s, "dedup_add_to_cart_cnt": c}
for (u, d, s), c in counts.items()
]
result.sort(key=lambda r: (str(r["user_id"]), r["local_dt"], str(r["sku"])))
return result