🚀 AI-Powered Mock Interviews Launching Soon - Join the Waitlist for Early Access

technicalmedium

Given an array of session objects with userId, startTime, and endTime, write a function that merges overlapping sessions per user and returns a dictionary mapping each userId to their total active time in seconds.

technical screen · 3-5 minutes

How to structure your answer

CIRCLES: Clarify the goal (total active time per user). Identify constraints (time format, overlapping logic). Recommend an algorithm (sort sessions per user, merge intervals). List steps (group by user, sort, iterate, merge, accumulate). Explain edge cases (touching intervals, invalid timestamps). Summarize complexity (O(n log n) time, O(n) space).

Sample answer

To compute total active time per user, first group the session objects by userId. For each user, sort their sessions by startTime. Then iterate through the sorted list, maintaining a current interval. If the next session starts before or at the current interval’s end, extend the current interval’s end to the maximum of the two ends; otherwise, add the length of the current interval to a running total and start a new current interval. After processing all sessions, add the last interval’s length. This approach runs in O(n log n) time due to sorting and O(n) space for grouping. Edge cases—such as sessions that touch but do not overlap, or sessions with identical timestamps—are handled by treating touching intervals as non‑overlapping. The final dictionary maps each userId to the sum of merged interval durations in seconds.

Key points to mention

  • • O(n log n) sorting per user ensures scalability.
  • • Handle edge cases where sessions touch but do not overlap.
  • • Return total active time in seconds for each user.

Common mistakes to avoid

  • âś— Assuming input sessions are pre‑sorted.
  • âś— Using nested loops leading to O(n²) complexity.
  • âś— Ignoring edge cases where endTime < startTime.