Hours Spent in Each Account Status from a Status Change Log
Last updated: November 29, 2026
Quick Overview
An integrity system logs account status changes (user_id, changed_at, status) with statuses like active, restricted and disabled. For a reporting window [start, end), compute total hours each user spent in each status, using the last status before the window as the starting state.
Meta
November 29, 20260
0
0 solved
An integrity system logs account status changes (user_id, changed_at, status) with statuses like active, restricted and disabled. For a reporting window [start, end), compute total hours each user spent in each status, using the last status before the window as the starting state.
Meta integrity teams measure how long accounts sit in restricted states to track enforcement fairness and appeal latency. This onsite question tests turning an event log into intervals with shift, clipping to a window, and carrying in state from before the window, which many candidates miss.
What the Interviewer Expects
- Derive interval end as the next change time per user with groupby shift
- Use the window end for the last open interval
- Clip interval starts and ends to the reporting window
- Include the state carried in from before the window start
- Drop zero-length or out-of-window intervals and aggregate hours
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you compute the median time to reinstatement after a restriction?
- What if the log has duplicate events with the same status back to back?
- How would you do this for 3 billion accounts without a groupby shift on the whole log?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
changes(user_id, changed_at, status), where each row means the account entered status at changed_at and stays there until the next row. Users whose first change is inside the window have no know...
Approach
Sort by user and time and set next_at = groupby(user).changed_at.shift(-1), filling the last one with the window end. Each row is now an interval [changed_at, next_at). Clip with `start_c = max(chan...