Problem 353751 · hard · Phase 03 Linear Management & Searching

Coincidences Across Three Detectors

two pointers · merging sorted lists · counting · tie-breaking

Three particle detectors log the times of their hits. The logs a, b and c are each sorted in non-decreasing order. A coincidence is a choice of one hit from each log (by position) such that the latest of the three times minus the earliest is at most d.

Return the number of coincidences.

Examples

Input:  a = [1, 5, 9], b = [2, 6], c = [3, 4, 10], d = 2
Output: 2
Explanation: (1, 2, 3) spans 2 and (5, 6, 4) spans 2. Every other choice spans more.

Input:  a = [4, 4], b = [4], c = [4, 4, 4], d = 0
Output: 6
Explanation: all 2 * 1 * 3 choices have the same time.

Input:  a = [1, 2, 3], b = [1, 2, 3], c = [1, 2, 3], d = 1
Output: 15

Constraints

  • 0 <= len(a), len(b), len(c) <= 3 * 10**4
  • -10**9 <= time <= 10**9, 0 <= d <= 2 * 10**9
  • If any log is empty the answer is 0. Trying every pair from two logs is already too slow.

Goals

  • Count each triple exactly once by charging it to its smallest member
  • Break ties between lists with a fixed order so equal values are never double-counted
  • Keep monotone pointers into several sorted lists at once
Starting Python…