Calculate Average Camera Switches per Session
Company: Snapchat
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Technical Screen
Given the PostgreSQL table:
```sql
camera_events (
event_id BIGINT PRIMARY KEY,
session_id BIGINT NOT NULL,
event_ts TIMESTAMP NOT NULL,
camera_position TEXT NOT NULL CHECK (camera_position IN ('front', 'rear'))
)
```
A camera switch occurs when an event's `camera_position` differs from the immediately preceding camera event in the same session. The first event in a session is not a switch.
Write one read-only `SELECT`/CTE query that returns the average number of camera switches per session across all sessions represented in the table.
Return exactly one row and one column:
```text
average_switches_per_session
```
### Constraints and Clarifications
- Order events within a session by `event_ts`, then `event_id` to break ties.
- Repeated consecutive records of the same position do not count as switches.
- Sessions with one event contribute zero switches and must remain in the denominator.
- Return a numeric result, not integer division; an empty table may return `NULL`.
```hint Compare adjacent rows
Use a window function to expose the preceding position, turn each comparison into zero or one, aggregate per session, and then average.
```
### Evaluation Focus
- Correct use of `LAG` within each session.
- Inclusion of zero-switch sessions.
- Deterministic ordering and a numeric average.
- A single read-only statement with the exact output alias.
### Extension
How would you compute the distribution of switch counts rather than only the average?
Overview: Calculate average front-to-rear camera switches per session in PostgreSQL. Use LAG, preserve one-event sessions in the denominator, and avoid integer-division errors.
Read the full Snapchat Data Scientist interview experience this question came from
Given camera_events, calculate the average number of camera switches per session across all sessions represented in the table. A switch occurs when camera_position differs from the immediately preceding event in the same session after ordering by event_ts and then event_id. The first event in each session is not a switch, repeated consecutive positions do not count, and one-event sessions contribute zero. Return exactly one numeric column named average_switches_per_session; an empty table may return NULL.
Tables
camera_events(event_id BIGINT, session_id BIGINT, event_ts TIMESTAMP, camera_position TEXT)
Hints
- Compare adjacent events within each session after applying the required deterministic ordering, then aggregate at the session grain before averaging.