Social feed~20 min2s · 256 MBtarget O(total + r log r) time, O(total) spacehashing
A social feed app suggests people to a group of friends who plan an event together. It looks at the friend list of each member of the group.
A person is a good suggestion when they are on the friend lists of enough members, and they are not a member of the group themselves. The app wants all such people, in order of their ids.
Write shared_friends(owners, lists, need).
owners[i] is a member of the group, and lists[i] is that member's friend list. The members are all different, and each friend list has no repeated id.need of the friend lists, and who are not among owners.Input: owners = [1, 2, 3], lists = [[2, 4, 5, 6], [1, 4, 6, 7], [1, 2, 4, 8]], need = 2
Output: [4, 6]The trace counts the lists each person outside the group is on. The members 1, 2 and 3 are skipped.
| Person | On the lists of | Count | At least 2? |
|---|---|---|---|
| 4 | 1, 2, 3 | 3 | yes |
| 5 | 1 | 1 | no |
| 6 | 1, 2 | 2 | yes |
| 7 | 2 | 1 | no |
| 8 | 3 | 1 | no |
Person 4 is on all three lists, and person 6 is on two. The members 1 and 2 are on other members' lists, but they are in the group, so they are skipped. The output is 4 and 6.
Input: owners = [10, 20], lists = [[30], [40]], need = 2
Output: []Persons 30 and 40 are each on one list only, and the group needs 2. The output is empty.
Input: owners = [5], lists = [[7, 8, 9]], need = 1
Output: [7, 8, 9]One member, and every friend is on at least one list. The output is 7, 8 and 9, in increasing order.
1 ≤ owners.length ≤ 1,000; lists has the same length1 ≤ need ≤ 1,000There are at most 10^5 ids in all. Counting how many lists contain each person by scanning every list for every person costs up to 10^5 × 1,000 × 100 = 10^10 steps. One pass that adds 1 to a map entry for each id in each list costs about 10^5 steps. Sorting the answer costs at most 10^5 × log(10^5).