Wedding Camera Timeline

HardheapAlso known as Merge k Sorted Lists

A wedding photographer ran several cameras all day: her own, an assistant's, a drone, and a few cameras clipped to the tables. Each camera's photos are already in time order. Times are seconds relative to the start of the ceremony, so a shot taken 10 minutes before it is -600.

She wants one album timeline for the couple, with every photo from every camera in time order. Some cameras took thousands of shots, some took none, and two cameras can fire at the very same second.

Your task

Write mergeTimelines(cameras). cameras is a list of lists; each inner list holds one camera's photo times in non-decreasing order. Return a single list with every time from every camera, in non-decreasing order. Keep repeated times: each one is a separate photo.

An empty cameras list, or cameras with no photos, give an empty result. Aim for O(N log k) time for N photos and k cameras.

mergeTimelines(cameras: int[][]) → int[]

Examples

Example 1
Input
cameras = [[-600, 0, 45], [-30, 10], [5, 45, 90]]
Output
[-600, -30, 0, 5, 10, 45, 45, 90]
Why

At each step, look only at the earliest unused photo of each camera and take the smallest: -600, then -30, then 0, 5, 10. Both 45s are kept because they are two different photos.

Example 2
Input
cameras = [[], [12, 12], []]
Output
[12, 12]
Why

Two cameras took nothing. The result is just the other camera's photos.

Example 3
Input
cameras = []
Output
[]
Why

No cameras at all: an empty timeline.

Constraints

  • 0 ≤ k = cameras.length ≤ 1,000
  • 0 ≤ cameras[i].length ≤ 2,000, and N, the total number of photos, is at most 50,000
  • -36,000 ≤ each time ≤ 86,400
  • Each cameras[i] is sorted in non-decreasing order.
Start with brute force

Two obvious ways. One: pour every photo into one list and sort it. That is O(N log N) and correct, but it throws away the fact that each camera is already sorted, and it needs all photos in memory before producing the first one.

Two: merge the cameras one at a time into a growing album. The album gets merged again and again, so early photos are copied up to k times: O(N · k), which is 50 million steps for 50,000 photos on 1,000 cameras. Scanning all k camera fronts for each photo is O(N · k) too.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code