Social feed~30 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spaceclassic twin: lc-444topological-sort
A shared photo album has n photos, numbered from 0. The true order of the photos is lost. Several editors each wrote a log: a list of some of the photos, in the order the editor saw them. The photos in one log are all different, and each log keeps the true relative order.
The app wants to know how open the order still is. It rebuilds the order one place at a time, always placing the smallest-numbered photo that nothing else must precede. At each place it asks whether the logs allow more than one photo.
Write count_open_choices(n, logs).
logs[i] lists photos in the order seen. Two photos next to each other in a log give a rule: the first goes before the second.-1 when the rules contradict each other, so that not every photo can be placed.Input: n = 6, logs = [[0,2,4],[1,2],[3,4,5],[0,1]]
Output: 3The rules are 0 before 2, 2 before 4, 1 before 2, 3 before 4, 4 before 5 and 0 before 1. A heap holds the ready photos.
| Place | Ready photos | More than one? | Photo placed |
|---|---|---|---|
| 1 | 0, 3 | yes | 0 |
| 2 | 1, 3 | yes | 1 |
| 3 | 2, 3 | yes | 2 |
| 4 | 3 | no | 3 |
| 5 | 4 | no | 4 |
| 6 | 5 | no | 5 |
Three places are open, so the answer is 3.
Input: n = 4, logs = [[0,1,2],[2,3]]
Output: 0The logs fix the order 0, 1, 2, 3. No place has a choice.
Input: n = 2, logs = [[0,1],[1,0]]
Output: -1One log puts photo 0 first, and the other puts photo 1 first. No order satisfies both.
1 ≤ n ≤ 100,0001 ≤ logs.length ≤ 100,000, each log has 1 to 20 photos from 0 to n - 1, and the photos in one log are differentScanning all photos and all rules to find the ready ones at every place costs about n × (n + m), which is about 2.5 × 10^10 steps for n = 100,000. Counting the photos each photo waits for, and keeping the ready ones in a heap, costs O((n + m) log n).