Interview Puzzles · Problem 99 of 118

Streaks of Active Months

HardInterview PuzzlesBank data

For account 254, find each streak of consecutive calendar months that had at least one transaction. Return start_month, end_month (both like '2025-06') and months (the length of the streak). Sort by start_month.

Hint 1

Turn each month into a number, for example year * 12 + month, and take the distinct months.

Hint 2

Number the distinct months in order with ROW_NUMBER(). Inside a streak, month number minus row number stays constant; it changes when there is a gap.

Reference solution

WITH months AS (
  SELECT DISTINCT CAST(STRFTIME('%Y', txn_date) AS INTEGER) * 12 + CAST(STRFTIME('%m', txn_date) AS INTEGER) AS m
  FROM transactions
  WHERE account_id = 254
), grouped AS (
  SELECT m, m - ROW_NUMBER() OVER (ORDER BY m) AS grp
  FROM months
)
SELECT PRINTF('%04d-%02d', (MIN(m) - 1) / 12, (MIN(m) - 1) % 12 + 1) AS start_month,
       PRINTF('%04d-%02d', (MAX(m) - 1) / 12, (MAX(m) - 1) % 12 + 1) AS end_month,
       COUNT(*) AS months
FROM grouped
GROUP BY grp
ORDER BY MIN(m);

This is the famous gaps and islands problem. If the values are consecutive, value - row_number is the same constant for all of them, because both grow by one at each step. When there is a gap, the value jumps but the row number does not, so the constant changes: it labels each "island". Grouping by that label gives the streaks. The same trick finds login streaks, consecutive days of sales, uninterrupted subscriptions and runs of identical statuses. Month 1 to 12 is mapped with (m - 1) / 12 and (m - 1) % 12 + 1 because month 12 would otherwise be confused with month 0 of the next year.