Payments app~35 min2s · 256 MBtarget O(n α(n)) time, O(n) spaceunion-find
A wallet app looks for fraud rings. An account logs in from a device, and that login links the two. Accounts that have logged in from the same device belong to the same ring. So does any account that shares a device with a member.
The fraud desk wants to watch rings grow. After every login, it needs the number of accounts in the largest ring.
Write largest_ring_after_each_login(accounts, devices, login_accounts, login_devices).
accounts accounts, numbered 0 to accounts - 1, and devices devices, numbered 0 to devices - 1.k links account login_accounts[k] to device login_devices[k]. The same pair may appear more than once.Input: accounts = 6, devices = 3, login_accounts = [0, 1, 2, 3, 1, 4, 5, 2], login_devices = [0, 0, 1, 1, 2, 2, 0, 2]
Output: [1, 2, 2, 2, 2, 3, 4, 6]The trace lists the ring of the account that logged in last.
| Login | Account | Device | Accounts in its ring | Largest ring |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 1 |
| 1 | 1 | 0 | 0, 1 | 2 |
| 2 | 2 | 1 | 2 | 2 |
| 3 | 3 | 1 | 2, 3 | 2 |
| 4 | 1 | 2 | 0, 1 | 2 |
| 5 | 4 | 2 | 0, 1, 4 | 3 |
| 6 | 5 | 0 | 0, 1, 4, 5 | 4 |
| 7 | 2 | 2 | 0, 1, 2, 3, 4, 5 | 6 |
Login 1 puts accounts 0 and 1 on device 0. Login 5 brings in account 4 through device 2. Login 7 links account 2 to device 2. That joins the ring of 2 and 3 to the ring of 0, 1, 4 and 5, so the largest ring has all 6 accounts.
Input: accounts = 3, devices = 2, login_accounts = [0, 0, 0], login_devices = [0, 0, 1]
Output: [1, 1, 1]Only account 0 ever logs in, three times. It never shares a device with another account, so every ring has one account.
Input: accounts = 4, devices = 1, login_accounts = [3, 2, 1, 0], login_devices = [0, 0, 0, 0]
Output: [1, 2, 3, 4]All four accounts use the same device. The ring grows by one account with each login.
1 ≤ accounts, devices ≤ 100,0001 ≤ login_accounts.length ≤ 200,000; login_devices has the same length0 ≤ login_accounts[k] < accounts and 0 ≤ login_devices[k] < devicesRecomputing every ring after every login costs about n × (accounts + devices + n) steps, about 10^11 here. Rings only merge and never split, and each login adds a single link. A union-find structure handles one link in almost constant time, so 2 × 10^5 logins are easy.