Find the week an account starts drifting away

Agent buildEasy10 minSalesforce style

Your task

Customer success keeps learning that accounts went quiet only after they churned. An agent watches each account's weekly usage and flags the week a real decline begins, measured against the account's own history.

Write first_churn_flag_week(weekly_usage, baseline_weeks, drop_percent, sustained_weeks): the rule your agent follows for each account.

  • weekly_usage (list of int): the account's usage per week, oldest first.
  • baseline_weeks (int): how many of the first weeks form the account's baseline.
  • drop_percent (int): how far below the baseline mean a week must fall to count as a drop.
  • sustained_weeks (int): how many drop weeks in a row raise the flag.
  • Return the index of the week the flag fires, or -1 if it never does.

Rules:

  1. If baseline_weeks or sustained_weeks is below 1: return -1.
  2. If there is no week after the baseline (the list has baseline_weeks entries or fewer): return -1.
  3. The baseline sum is the total of the first baseline_weeks weeks. If it is 0 or less: return -1.
  4. A week after the baseline is a drop week if its usage is at most 100 - drop_percent percent of the baseline mean. Check it in whole numbers: usage * 100 * baseline_weeks <= baseline_sum * (100 - drop_percent).
  5. Count drop weeks in a row, starting after the baseline. A week that is not a drop week resets the count to 0. Return the index of the week where the count reaches sustained_weeks, or -1 if it never does.

Examples

first_churn_flag_week(weekly_usage: list[int], baseline_weeks: int, drop_percent: int, sustained_weeks: int) -> int
Example 1
Inputfirst_churn_flag_week([10, 10, 10, 10, 4, 4, 4], 4, 50, 2)
Output5
Example 2
Inputfirst_churn_flag_week([10, 10, 10, 10, 4, 9, 4, 4], 4, 50, 2)
Output7
Example 3
Inputfirst_churn_flag_week([8, 8, 8, 8, 8, 8], 4, 50, 2)
Output-1