KatInterview

Calculate Spend Percentage of High-Volume Spenders

Arrays & HashingAuto-graded · 21 test cases
EasyAuto-gradedArrays & Hashingarrayshash tabledata manipulation

Last updated

Compute the share of 2023 total expenditure contributed by users who met a high-tier spending threshold in 2022.

You are analyzing ad expenditure data across different calendar years. You are given a list of transactions, where each entry is represented as [user_id, spend, transaction_date].

  • user_id is an integer identifying the user.
  • spend is a numeric value (integer or float) indicating the transaction amount.
  • transaction_date is a string formatted as "YYYY-MM-DD" (or a standard date representation).

A user is designated as a "Whale" if their cumulative expenditure across all transactions in the calendar year 2022 is $10,000 or more.

Your goal is to determine what percentage of the total expenditure in 2023 (across all users) was generated by these 2022 Whales.

Specifically, calculate: $$\text{Percentage} = \left( \frac{\text{Total 2023 spend by 2022 Whales}}{\text{Total 2023 spend by all users}} \right) \times 100$$

Specifications & Edge Cases

  • The threshold filter of $10,000 applies to the sum of all transactions by a user in 2022, not to individual purchases.
  • The denominator includes all spend in 2023 from all users, whether they were 2022 Whales, non-Whales, or new users in 2023.
  • If total expenditure in 2023 across all users is 0 (or if there are no 2023 transactions), return 0.0.
  • Transactions occurring in years other than 2022 and 2023 should be ignored.
  • Return an exact float representing the percentage on a scale of 0.0 to 100.0.

Constraints

  • 0 <= len(rows) <= 10^5
  • For each row: user_id is a positive integer, spend is a non-negative float/int, and transaction_date is a valid date string or date object.

Examples

Example 1

Input: whale_spend_share([[1, 12000, '2022-05-10'], [2, 500, '2022-06-15'], [1, 2000, '2023-01-20'], [3, 5000, '2023-02-10']])

Output: 28.57142857142857

Example 2

Input: whale_spend_share([[1, 6000, '2022-01-01'], [1, 4000, '2022-12-31'], [1, 2500, '2023-03-01'], [2, 7500, '2023-04-01']])

Output: 25

Hints

Hint 1

Aggregate the total spend per user specifically for transactions occurring in the year 2022.

Hint 2

Identify all user_ids whose 2022 cumulative spend reaches or exceeds 10,000.

Hint 3

Sum the 2023 spend for these high-value users, then divide by the 2023 spend of all users combined, multiplied by 100.