Wedding Camera Timeline

HardheapAlso known as Merge k Sorted Lists

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

She wants one album with every photo in time order. Some cameras took thousands of shots, some none, and two can fire in the 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

There are no cameras at all, so the timeline is empty.

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

Pour every photo into one list and sort it. That is O(N log N) and correct, but ignores that each camera is already sorted, and needs all photos in memory before producing the first.

Or merge cameras one at a time into a growing album. Early photos get copied up to k times: O(N · k), 50 million steps for 50,000 photos on 1,000 cameras. Scanning all k fronts per 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