On a hike you took photos while a GPS watch recorded your location now and then. You have two lists of times in seconds, both sorted: when each photo was taken and when each location reading was recorded. A photo and a reading match when their times are at most d seconds apart, so that reading tells you roughly where the photo was taken.
Write count_matches(photos: list[int], readings: list[int], d: int) -> int that returns the number of index pairs (i, j) with abs(photos[i] - readings[j]) <= d.
count_matches([10, 20, 30], [12, 18, 40], 3) # 2 (10,12) and (20,18)
count_matches([5, 5], [5, 7], 2) # 4 every photo matches every reading
count_matches([], [1, 2], 10) # 0
- Up to
10^5times per list, in[0, 10^9], possibly repeated. - Don't use
bisect: the point is to walk the pointers. - ⭐ Bonus: a speed test at full size earns a star in O(n + m).
Show hint
as photo times rise, the window [photo - d, photo + d] only moves right. Advance two indexes into readings (first >= photo - d, first > photo + d) and add the gap.