KatInterview

Mean Front-to-Rear Lens Flips Across Recorded Sessions

Arrays & HashingAuto-graded · 15 test cases
MediumAuto-gradedArrays & Hashinghash-mapgroupingsorting

Last updated

Group event logs by session, sort chronologically, count adjacent front-then-rear transitions, and average over all sessions, including sessions with zero flips.

A camera app records every time a user selects a lens during a usage session. Each lens selection is either "front" (selfie) or "rear" (world-facing).

You are given a list of event records. Each record is a list of four values:

[event_id, session_id, camera_mode, event_time]

  • event_id is an integer identifying the event.
  • session_id is a string identifying the session the event belongs to.
  • camera_mode is either "front" or "rear".
  • event_time is a timestamp string in the format "YYYY-MM-DD HH:MM:SS".

The records may arrive in any order.

Task

Compute the average number of front-to-rear flips per session.

Within a single session, sort the events by event_time in ascending order. A front-to-rear flip occurs at an event whose mode is "rear" when the event directly before it in that same session's sorted order has mode "front". Events from different sessions never form a flip together. Only the adjacent pair counts: front, front, rear yields one flip, and rear, front yields none.

If two events in the same session have the same event_time, keep them in the order they appeared in the input.

Every distinct session_id that appears in the input counts toward the average, including sessions with a single event and sessions with no flips.

Output

Return the total number of flips across all sessions divided by the number of distinct sessions, as a float rounded to 2 decimal places. If the input list is empty, return 0.0.

Constraints

  • 0 <= len(rows)
  • camera_mode is always "front" or "rear".
  • Timestamps use a fixed-width format, so comparing them as strings gives chronological order.
  • Use true (floating-point) division, not integer division.
  • Round the final result to 2 decimal places.

Examples

Example 1

Input: mean_front_to_rear_flips([[1, 's1', 'front', '2024-01-01 10:00:00'], [2, 's1', 'rear', '2024-01-01 10:00:05'], [3, 's1', 'front', '2024-01-01 10:00:10'], [4, 's1', 'rear', '2024-01-01 10:00:15'], [5, 's2', 'rear', '2024-01-01 11:00:00'], [6, 's2', 'front', '2024-01-01 11:00:04'], [7, 's3', 'front', '2024-01-01 12:00:00']])

Output: 0.67

Hints

Hint 1

Group the records by session_id first; flips never cross a session boundary.

Hint 2

Within each group, sort by event_time (a stable sort keeps input order for ties), then scan adjacent pairs looking for front followed by rear.

Hint 3

The average over sessions equals total flips divided by the number of distinct sessions, so sessions with zero flips must still be counted in the denominator. Handle the empty input separately.