Count Speaker Switches in Each Messenger Conversation
Last updated: November 29, 2026
Quick Overview
For every one-to-one Messenger conversation, count the number of times the sender changes between consecutive messages and the number of conversational turns, where a turn is a maximal run of messages from the same sender.
Meta
November 29, 20260
0
0 solved
For every one-to-one Messenger conversation, count the number of times the sender changes between consecutive messages and the number of conversational turns, where a turn is a maximal run of messages from the same sender.
Messenger teams use back-and-forth turn counts as a proxy for real conversation versus one-sided broadcasting. The interviewer is checking LAG over a correctly ordered partition and whether you see that turns equal switches plus one.
What the Interviewer Expects
- Orders messages within a conversation by timestamp with a tie-break
- Uses LAG(sender_id) to compare with the previous message
- Counts switches where the previous sender exists and differs
- Derives turns as rows that start a new run
- Reasons about single-message conversations
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 number of turns per conversation for conversations started from a Marketplace listing?
- How would you measure the average response time at each switch?
- How would you extend this to group chats where 'switch' means a different sender than the previous message?
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
Table: messages(message_id, conversation_id, sender_id, sent_at). Conversations are one-to-one. I will order by sent_at, message_id since rapid messages can share a millisecond timestamp....
Approach
LAG(sender_id) per conversation gives the previous sender. A switch is a row where the previous sender is not NULL and differs. A turn starts on every row where the previous sender is NULL (first me...