Daily Session Starters: Count Users Who Opened the App First
SQL & DataAuto-graded · 18 test casesLast updated
Tests window-function thinking, tie-breaking logic, and grouped aggregation by finding users whose very first recorded action each day was opening the app.
Background
You are working with a stream of telemetry records from a mobile app. Every time a user interacts with the app, a record is written to an events log. Each record carries a precise timestamp, a unique record ID, the action performed, and the device that generated it.
Your task is to figure out, for each calendar day, how many distinct users began that day by opening the app — and break those counts down by the operating system and device model tied to that opening action.
Input Format
You receive a list of event records. Each record is a dictionary with the following fields:
| Field | Type | Description |
|---|---|---|
event_id | int | Globally unique record identifier |
user_id | int | Identifier for the user who triggered the event |
event_name | str | Label for the action (e.g. "app_launch", "send_chat", "open_camera") |
event_timestamp | str | ISO-format timestamp string ("YYYY-MM-DD HH:MM:SS") |
os | str | Operating system on the device (e.g. "iOS", "Android") |
device_model | str | Hardware model name (e.g. "iPhone 15", "Pixel 8") |
Task
Implement tally_app_launch_openers(events) that returns a list of dictionaries. Each dictionary represents one (date, os, device_model) combination where at least one user's very first action of the day was "app_launch".
Definitions and Rules
- Calendar day: determined by the date portion of
event_timestamp(i.e. theYYYY-MM-DDprefix, ignoring the time-of-day). - First event of the day for a user: the record with the earliest
event_timestampamong all records sharing the sameuser_idand calendar day. If two records have identical timestamps, the one with the smallerevent_idwins. - Qualifying user: a user whose first event of the day (by the rule above) has
event_name == "app_launch". A user who triggers an"app_launch"later in the day but not as their very first event does not qualify for that day. - Output rows: for every
(event_date, os, device_model)tuple that has at least one qualifying user, emit a dictionary with keysevent_date,os,device_model, anduser_count.event_dateis an ISO date string ("YYYY-MM-DD").user_countis the number of distinct qualifying users for that combination.
- Output order: sort results by
event_dateascending, thenosascending, thendevice_modelascending. - Omit any combination with zero qualifying users — do not emit rows with
user_count = 0.
Constraints
0 <= len(events) <= 10^6event_idvalues are unique across the entire input.user_idis a positive integer.event_timestampis a valid ISO-format datetime string with no timezone component.osanddevice_modelare non-empty strings.- A user may appear on multiple days and across multiple devices; each day is evaluated independently.
- The input list is not guaranteed to be sorted in any particular order.
Examples
Example 1
Input: tally_app_launch_openers([{'event_id': 101, 'user_id': 1, 'event_name': 'app_launch', 'event_timestamp': '2024-03-01 08:00:00', 'os': 'iOS', 'device_model': 'iPhone 15'}, {'event_id': 102, 'user_id': 1, 'event_name': 'send_chat', 'event_timestamp': '2024-03-01 08:05:00', 'os': 'iOS', 'device_model': 'iPhone 15'}, {'event_id': 103, 'user_id': 2, 'event_name': 'open_camera', 'event_timestamp': '2024-03-01 09:00:00', 'os': 'Android', 'device_model': 'Pixel 8'}, {'event_id': 104, 'user_id': 2, 'event_name': 'app_launch', 'event_timestamp': '2024-03-01 09:10:00', 'os': 'Android', 'device_model': 'Pixel 8'}, {'event_id': 105, 'user_id': 3, 'event_name': 'app_launch', 'event_timestamp': '2024-03-01 07:30:00', 'os': 'iOS', 'device_model': 'iPhone 15'}, {'event_id': 106, 'user_id': 3, 'event_name': 'app_launch', 'event_timestamp': '2024-03-02 10:00:00', 'os': 'iOS', 'device_model': 'iPhone 15'}])
Output: [{'event_date': '2024-03-01', 'os': 'iOS', 'device_model': 'iPhone 15', 'user_count': 2}, {'event_date': '2024-03-02', 'os': 'iOS', 'device_model': 'iPhone 15', 'user_count': 1}]
Example 2
Input: tally_app_launch_openers([{'event_id': 10, 'user_id': 7, 'event_name': 'app_launch', 'event_timestamp': '2024-05-10 12:00:00', 'os': 'Android', 'device_model': 'Pixel 8'}, {'event_id': 9, 'user_id': 7, 'event_name': 'send_chat', 'event_timestamp': '2024-05-10 12:00:00', 'os': 'iOS', 'device_model': 'iPhone 14'}])
Output: []
Hints
Hint 1
Start by finding the single earliest event per (user, day) pair before doing any filtering — applying an event_name filter first changes the question entirely.
Hint 2
To pick the winner among tied timestamps, compare (timestamp, event_id) as a tuple; Python tuple comparison handles the two-level sort in one expression.
Hint 3
Once you have one winning record per (user, day), filter to app_launch winners and use a dictionary keyed on (event_date, os, device_model) to accumulate counts; sorting that dictionary's items at the end handles the required output order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a "first record per group, then filter and aggregate" pattern. The order of these steps is what makes or breaks correctness.
Why filtering early is wrong
It is tempting to discard non-app_launch rows up front, but that transforms the question from "did this user's very first action happen to be a launch?" into "what was the user's earliest launch of the day?" Those are different questions. A user who opens the camera at 09:00 and then launches the app at 09:10 would be incorrectly counted if you filter first.
Step-by-step plan
1. Find each user's first event of the day.
Iterate every record and maintain a dictionary keyed on (calendar_day, user_id). The value stored is the current best candidate for that user on that day. A candidate is better than the incumbent when its (timestamp, event_id) pair is strictly smaller — this gives the required two-level tie-break in a single comparison.
candidate[:2] < current[:2] # compares (timestamp, event_id)
After the full pass, the dictionary holds exactly one record per (user, day) pair — the winner.
2. Filter and count.
Walk the winners. Skip any whose event_name is not "app_launch". For the rest, increment a counter keyed on (event_date, os, device_model). Because each (user, day) pair contributes at most one winner, this counter directly equals the number of distinct qualifying users per group.
3. Sort and format.
sorted(counts.items()) sorts by the (day, os, device_model) tuple. ISO date strings sort chronologically as plain strings, so the resulting order matches the required event_date ASC, os ASC, device_model ASC.
Why it is correct
- The partition key
(user_id, day)does not include device or OS, so the "first event" is the first across all of the user's devices on that day — the device attributes come from whichever event wins. (timestamp, event_id)is a total order becauseevent_idis globally unique, making the winner deterministic even under exact timestamp ties.- Each key appears once in
first_events, so each qualifying user contributes exactly+1to their group counter. No double-counting is possible. - Groups with zero qualifying users never get a key in
counts, so requirement 6 (omit zero-count rows) is satisfied automatically.
Complexity
- Time: O(N) for the single scan to build
first_events, where N is the number of input records. O(G log G) to sort the G output groups, where G ≤ the number of distinct(day, user)pairs. In practice G ≪ N. - Space: O(U·D) for
first_events, where U is the number of unique users and D the number of distinct days. O(G) forcounts.
Edge cases
- Exact timestamp tie: the event with the smaller
event_idis chosen, even if neither or both are launches. - User whose only launch happens mid-day: excluded for that day.
- Empty input: both dictionaries stay empty; the function returns
[]. - Single user, multiple days: counted independently on each day.
- Input unsorted: neither phase relies on input order.
Reference solution
from collections import defaultdict
from datetime import datetime
from typing import Dict, List
def tally_app_launch_openers(events: List[Dict[str, object]]) -> List[Dict[str, object]]:
# Phase 1: keep only the earliest record per (user_id, calendar day).
# Tie-breaking: smaller event_id wins when timestamps are equal.
first_events: Dict[tuple, tuple] = {}
for event in events:
timestamp = datetime.fromisoformat(event["event_timestamp"])
day = timestamp.date().isoformat()
key = (day, event["user_id"])
# Compare (timestamp, event_id) — smaller wins; store full event for later.
candidate = (timestamp, event["event_id"], event)
current = first_events.get(key)
if current is None or candidate[:2] < current[:2]:
first_events[key] = candidate
# Phase 2: among winning records, count only app_launch events,
# grouped by (event_date, os, device_model).
counts: Dict[tuple, int] = defaultdict(int)
for (day, _), (_, _, event) in first_events.items():
if event["event_name"] == "app_launch":
counts[(day, event["os"], event["device_model"])] += 1
# Phase 3: build and sort the output list.
return [
{"event_date": day, "os": os, "device_model": model, "user_count": count}
for (day, os, model), count in sorted(counts.items())
]