Skip to the code
+10 XP

#454 Count Unique Shoppers After Each Merge

easy

An e-commerce site has n shopper accounts numbered 0 to n - 1. A cleanup job finds pairs of accounts that belong to the same person and reports them one at a time in merges. Merging is transitive: if a matches b and b matches c, all three are one shopper.

Write shoppersAfterMerges(n, merges) that returns an array with one number per merge: how many distinct shoppers there are right after that merge is applied.

Example 1

Input: n = 4, merges = [[0,1],[2,3],[1,0],[1,2]]
Output: [3,2,2,1]

Merging 0 and 1 leaves 3 shoppers, then 2 and 3 leaves 2. Merging 1 and 0 again changes nothing. Merging 1 and 2 joins everyone.

Example 2

Input: n = 2, merges = []
Output: []

No merges, so no counts to report.

Constraints

  • 1 <= n <= 100000
  • 0 <= merges.length <= 100000
  • 0 <= a, b < n
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).