Social feed~15 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-349hashing
A feed team tests two ranking rules. Each rule produced a list of post ids for the same user, and the lists are in the order the rules ranked them. They are not sorted by id, and an id can appear several times in one list.
The team wants the ids that both rules chose. Each shared id is reported once, in the order in which it first appears in the list of the first rule.
Each list can hold 100,000 ids, and either can be empty.
Write shared_ids(first, second).
first and second are lists of post ids in ranking order. They are not sorted.first.Input: first = [9, 4, 9, 5, 4, 8], second = [4, 9, 9, 7, 8, 4]
Output: [9, 4, 8]The second list holds the ids [4, 7, 8, 9]. The table walks the first list.
| Id | In the second list | Action |
|---|---|---|
| 9 | yes | kept |
| 4 | yes | kept |
| 9 | yes | already kept |
| 5 | no | skipped |
| 4 | yes | already kept |
| 8 | yes | kept |
Input: first = [3, 1, 2], second = [2, 3]
Output: [3, 2]The first list is not sorted, and the answer keeps its order: 3 comes before 2.
Input: first = [1, 2], second = []
Output: []An empty list shares nothing.
0 ≤ first.length, second.length ≤ 100,000 (ids per rule)1 ≤ first[i], second[i] ≤ 1,000,000,000 (post id)Looking up each id of the first list by scanning the second list costs about 10,000,000,000 comparisons for two lists of 100,000 ids.
A set of the second list answers each lookup in one step, so about 200,000 steps are enough. Sorting both lists would also work, but it would cost O(n log n) and change the order of the answer.