Park Ticket Revenue and Pass-Holder Visit Averages
SQL & DataAuto-graded · 4 test casesLast updated
Aggregate ticket revenue and shares, then compute average distinct in-period visits per annual-pass period, including zero-visit passes, to project total entries.
Park Ticket Revenue and Pass-Holder Visit Averages
An amusement park keeps four datasets. Implement a function that turns them into a revenue breakdown and a projection of total park entries. It receives plain Python lists of dictionaries instead of database tables, but the logic is the same as the equivalent SQL joins and aggregations.
Inputs
ticket_catalog: a list of dicts, one per ticket type, with keys:id(int)name(str)price_usd(int)duration_days(int)
units_sold_rows: a list of dicts with keysticket_type_id(int) andunits_sold(int). It gives the number of units sold in the last fiscal year. Each ticket type appears at most once, and everyticket_type_idexists inticket_catalog. A catalog type with no row sold 0 units.pass_periods: a list of dicts with keysuser_id,start_dateandend_date. Dates are ISO strings ("YYYY-MM-DD"). Each dict is one annual pass. A user may appear several times, once per pass.visit_log: a list of dicts with keysuser_idandvisit_date(ISO string). One user may have many visits, including several records on the same day.
What to compute
Revenue. For each ticket type, revenue is price_usd * units_sold. The revenue share is that revenue divided by total revenue across all types. If total revenue is 0, every share is 0.0.
Entries model.
- Every ticket type whose
nameis not"annual_pass"givesduration_daysentries per unit sold. Sumunits_sold * duration_daysover these types to getconstant_entries. - The ticket type named
"annual_pass"gives an unknown number of entries per unit. Report its total units sold asannual_pass_units. If no such type has sales, this is 0.
Average visits per pass period. For each element of pass_periods, count the distinct visit dates of the same user that fall within [start_date, end_date], with both ends inclusive. Visits outside the period do not count. Several records on the same date count once. Treat each pass period as its own holder, even if the same user has several. Periods with zero qualifying visits stay in the average. Average the counts over all pass periods. If there are no pass periods, the average is 0.0.
Total entries. total_entries = constant_entries + annual_pass_units * average_visits.
Output
Return a dict with exactly these keys:
"revenue_by_ticket_type": a list ordered by ticket typeidascending. Each item is a dict{"ticket_type": name, "revenue_usd": revenue, "revenue_share": share}."total_revenue_usd": the sum of all revenues."entries_as_function_of_x": a dict{"constant_entries": ..., "annual_pass_units": ...}."average_visits_per_pass_period": the average from above, as a float."total_entries": the projection from above.
Constraints
- Up to roughly 10^3 ticket types, 10^5 pass periods and 10^6 visit records.
- All dates are valid ISO dates, and
start_date <= end_datefor every pass. units_sold,price_usdandduration_daysare non-negative integers.- Visits by users with no pass period contribute nothing.
Examples
Example 1
Input: summarize_park_sales_and_passes([{'id': 1, 'name': 'single_day', 'price_usd': 80, 'duration_days': 1}, {'id': 2, 'name': 'five_day', 'price_usd': 300, 'duration_days': 5}, {'id': 3, 'name': 'annual_pass', 'price_usd': 1000, 'duration_days': 365}], [{'ticket_type_id': 1, 'units_sold': 250000}, {'ticket_type_id': 2, 'units_sold': 100000}, {'ticket_type_id': 3, 'units_sold': 10000}], [{'user_id': 1, 'start_date': '2024-03-15', 'end_date': '2025-03-14'}, {'user_id': 5, 'start_date': '2024-08-21', 'end_date': '2025-08-20'}], [{'user_id': 1, 'visit_date': '2024-06-10'}, {'user_id': 1, 'visit_date': '2024-06-11'}, {'user_id': 1, 'visit_date': '2024-07-01'}, {'user_id': 5, 'visit_date': '2024-09-01'}, {'user_id': 5, 'visit_date': '2024-09-15'}, {'user_id': 2, 'visit_date': '2024-06-15'}])
Output: {'revenue_by_ticket_type': [{'ticket_type': 'single_day', 'revenue_usd': 20000000, 'revenue_share': 0.3333333333333333}, {'ticket_type': 'five_day', 'revenue_usd': 30000000, 'revenue_share': 0.5}, {'ticket_type': 'annual_pass', 'revenue_usd': 10000000, 'revenue_share': 0.16666666666666666}], 'total_revenue_usd': 60000000, 'entries_as_function_of_x': {'constant_entries': 750000, 'annual_pass_units': 10000}, 'average_visits_per_pass_period': 2.5, 'total_entries': 775000}
Hints
Hint 1
Revenue is a per-type product, and the shares need the grand total, so compute revenues first and divide in a second pass.
Hint 2
Group the visit dates by user into sets so duplicates on the same day collapse, then check each pass period against only its own user's dates.
Hint 3
Iterate over pass periods, not over visits. That keeps zero-visit passes in the denominator, and a user with two passes counts twice.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has four small steps, and the third is the one that needs care.
-
Revenue and shares. Index the catalog by id and the sales rows by ticket type id. For each type in id order, revenue is
price_usd * units(0 units if there is no sales row). Add these up for the total, then do a second pass to set each share torevenue / total, or0.0when the total is 0. -
Entries model. Walk through the sales rows. For the type named
annual_pass, add its units toannual_pass_units. For every other type, addunits * duration_daystoconstant_entries. Total entries are thenconstant_entries + annual_pass_units * X, whereXis the unknown average visits per pass. -
Empirical X. Build a map from user to the set of distinct visit dates. The set removes duplicate records on the same day. Then loop over the pass periods, not over the visits, and count the dates of that period's user that lie in
[start_date, end_date]. Averaging over every period gives:- zero-visit passes stay in the denominator, like a
LEFT JOINwith the date filter in theONclause; - a user with two passes counts as two periods, like grouping by
(user_id, start_date, end_date); - visits by users without a pass are ignored.
With no periods, the average is
0.0. - zero-visit passes stay in the denominator, like a
-
Plug in.
total_entries = constant_entries + annual_pass_units * average_visits.
Why it is correct
- Revenue is linear in units, and every share uses the same denominator, so the shares sum to 1 whenever the total is positive.
- A fixed-duration ticket yields exactly
duration_daysentries per unit, sounits * duration_daysis exact. - Iterating over pass periods makes each period contribute exactly one count, including 0. Using a set of dates counts each day once, and the inclusive comparison counts visits on the first and last day.
For the sample, the revenues are 20M, 30M and 10M, with shares 1/3, 1/2 and 1/6. Constant entries are 250,000 + 500,000 = 750,000. The two passes have 3 and 2 visits, so the average is 2.5 and total entries are 750,000 + 10,000 × 2.5 = 775,000.
Complexity
Let T be the number of ticket types, V the number of visits, and P the number of pass periods.
- Time: O(T + V + sum over periods of the distinct visit dates of that period's user). In the worst case this is O(T + V + P·V).
- Space: O(T + V).
Sorting each user's dates and using binary search would cut the per-period cost to logarithmic. In SQL, an index on visits(user_id, visit_date) gives the same effect.
Reference solution
from datetime import date
from typing import Dict, List
def summarize_park_sales_and_passes(ticket_catalog: List[Dict[str, object]], units_sold_rows: List[Dict[str, int]], pass_periods: List[Dict[str, object]], visit_log: List[Dict[str, object]]) -> Dict[str, object]:
types_by_id = {t['id']: t for t in ticket_catalog}
units_by_type = {r['ticket_type_id']: r['units_sold'] for r in units_sold_rows}
# Revenue per ticket type, ordered by id.
revenues = []
total_revenue = 0
for tid in sorted(types_by_id):
t = types_by_id[tid]
revenue = t['price_usd'] * units_by_type.get(tid, 0)
total_revenue += revenue
revenues.append({
'ticket_type': t['name'],
'revenue_usd': revenue,
'revenue_share': 0.0,
})
for row in revenues:
row['revenue_share'] = row['revenue_usd'] / total_revenue if total_revenue else 0.0
# Entries model: constant part and annual-pass units.
constant_entries = 0
annual_pass_units = 0
for tid, units in units_by_type.items():
t = types_by_id[tid]
if t['name'] == 'annual_pass':
annual_pass_units += units
else:
constant_entries += units * t['duration_days']
# Distinct visit dates per user.
dates_by_user = {}
for v in visit_log:
dates_by_user.setdefault(v['user_id'], set()).add(v['visit_date'])
# Distinct in-period visits for each pass period.
counts = []
for p in pass_periods:
start = date.fromisoformat(p['start_date'])
end = date.fromisoformat(p['end_date'])
count = 0
for d in dates_by_user.get(p['user_id'], set()):
if start <= date.fromisoformat(d) <= end:
count += 1
counts.append(count)
average_visits = (sum(counts) / len(counts)) if counts else 0.0
total_entries = constant_entries + annual_pass_units * average_visits
return {
'revenue_by_ticket_type': revenues,
'total_revenue_usd': total_revenue,
'entries_as_function_of_x': {
'constant_entries': constant_entries,
'annual_pass_units': annual_pass_units,
},
'average_visits_per_pass_period': average_visits,
'total_entries': total_entries,
}