Chat app~25 min2s · 256 MBtarget O(n + m α(n)) time, O(n) spaceunion-find
A chat app records which sign-in name each device has used. A device can use several sign-in names, and a sign-in name can be used on several devices.
Support staff treat two devices as belonging to the same person when they share a sign-in name, directly or through a chain of devices that share names. A device that never signed in belongs to its own person.
Support wants to know how many people own at least k devices.
Write people_with_many_devices(devices, accounts, logins, k).
devices is the number of devices, numbered 0 to devices - 1. accounts is the number of sign-in names, numbered 0 to accounts - 1.logins[i] is [device, account]: that device signed in with that name. The same pair can appear more than once.k devices.Input: devices = 6, accounts = 3, logins = [[0,0],[1,0],[2,1],[3,1],[1,1],[5,2]], k = 2
Output: 1The solution gives every device and every sign-in name a group of its own. Each login joins a device with its name. Then it counts the devices in every group.
| Login read | Group after it | Devices in the group |
|---|---|---|
[0,0] |
device 0 and name 0 | 1 |
[1,0] |
devices 0, 1 and name 0 | 2 |
[2,1] |
device 2 and name 1 | 1 |
[3,1] |
devices 2, 3 and name 1 | 2 |
[1,1] |
devices 0 to 3 and names 0, 1 | 4 |
[5,2] |
device 5 and name 2 | 1 |
Only the group of devices 0 to 3 has at least 2 devices, so one person qualifies. Device 4 never signed in, so it is a person with 1 device.
Input: devices = 6, accounts = 3, logins = [[0,0],[1,0],[2,1],[3,1],[1,1],[5,2]], k = 1
Output: 3With k = 1 every person counts: the owner of devices 0 to 3, the owner of device 4 and the owner of device 5.
Input: devices = 6, accounts = 3, logins = [[0,0],[1,0],[2,1],[3,1],[1,1],[5,2]], k = 5
Output: 0The biggest owner has 4 devices, so nobody has 5.
1 ≤ devices ≤ 100,000, 1 ≤ accounts ≤ 100,000 and 1 ≤ k ≤ devices0 ≤ len(logins) ≤ 200,000, and every login is [device, account] with 0 ≤ device < devices and 0 ≤ account < accountsComparing every pair of devices for a shared name costs about 100,000 times 100,000 steps, which is 10,000,000,000 checks. Each login can instead be read once, and that is 200,000 steps.