Payments app~25 min2s · 256 MBtarget O(c α(p)) time, O(p + c) spaceclassic twin: lc-721union-find
A payments app lets people create several profiles, and each profile lists the card fingerprints it has used. Two profiles that share a fingerprint belong to the same person, and so do profiles linked through a chain of such sharing.
Some fingerprints belong to shared kiosks and must never link two profiles. The app keeps a list of them.
Support wants to know how many people there are, and how many profiles the biggest person has.
Write people_after_merge(profiles, ignored).
profiles[i] lists the card fingerprints of profile i. A fingerprint can appear in many profiles.ignored lists the fingerprints of shared kiosks. A fingerprint in this list never links two profiles.[people, biggest]: the number of people, and the largest number of profiles that one person has.Input: profiles = [[1,2],[2,3],[4],[5,6],[3,7],[8,5]], ignored = []
Output: [3,3]The solution gives each profile a group of its own. It remembers the first profile that used each fingerprint, and joins a profile with that one when a fingerprint comes up again.
| Profile read | Fingerprints | What happens | Groups of profiles |
|---|---|---|---|
| 0 | 1, 2 | both are new | {0} |
| 1 | 2, 3 | 2 was used by profile 0, so join | {0,1} |
| 2 | 4 | new | {2} |
| 3 | 5, 6 | both are new | {3} |
| 4 | 3, 7 | 3 was used by profile 1, so join | {0,1,4} |
| 5 | 8, 5 | 5 was used by profile 3, so join | {3,5} |
There are 3 people. The biggest person has the 3 profiles 0, 1 and 4, so the answer is [3,3].
Input: profiles = [[1,2],[2,3],[4],[5,6],[3,7],[8,5]], ignored = [2]
Output: [4,2]Fingerprint 2 is a kiosk card, so it no longer links profiles 0 and 1. Profile 0 is alone, profiles 1 and 4 share fingerprint 3, and profiles 3 and 5 share fingerprint 5. That makes 4 people, and the biggest has 2 profiles.
Input: profiles = [[1,2],[2,3],[4],[5,6],[3,7],[8,5]], ignored = [2,3,5]
Output: [6,1]Every fingerprint that appears twice is ignored. All 6 profiles are different people with 1 profile each.
1 ≤ len(profiles) ≤ 50,000, and every profile lists between 1 and 10 fingerprints0 ≤ len(ignored) ≤ 1,000, and every fingerprint is between 0 and 1,000,000Comparing every pair of profiles costs about 1,250,000,000 pairs, and each comparison looks at up to 10 fingerprints. The fingerprints can instead be read once, and each profile joins the first profile that used the same fingerprint.