Social feed~30 min2s · 256 MBtarget O((n + m) α(n) + 26 n) time, O(n) spaceclassic twin: lc-1202union-find
A feed shows a row of cards, and each card has a type written as a lowercase letter. Editors may swap the cards in two slots, but only for pairs of slots on an approved list. They can use any approved swap, in any order, as often as they like.
Cards of the same type look the same, so two rows are the same when they show the same letters in the same slots. The team wants to know how many different rows the approved swaps can produce, including the current one.
Write count_arrangements(cards, swaps).
cards[i] is the type of the card in slot i.swaps[j] = [a, b] is an approved pair of different slots. A pair may be listed more than once.cards can become, including cards itself.1,000,000,007.Input: cards = "dcab", swaps = [[0, 3], [1, 2]]
Output: 4The slots form groups by their swaps, and slots in one group can trade cards in any pattern. The count is the product, over the groups, of the number of different ways to arrange the cards of the group.
| Group of positions | Cards there | Distinct arrangements |
|---|---|---|
| 0 and 3 | d, b |
2! = 2 |
| 1 and 2 | c, a |
2! = 2 |
There are 2 × 2 = 4 different rows: dcab, bcad, dacb and bacd.
Input: cards = "aab", swaps = [[0, 2], [1, 2]]
Output: 3All three slots are in one group with the cards a, a and b. Of the 6 orders of three cards, 3 are different strings: aab, aba and baa.
Input: cards = "xyz", swaps = []
Output: 1With no approved swap, the row cannot change, so there is 1 row.
1 ≤ len(cards) ≤ 100,000, and every card is a lowercase letter0 ≤ len(swaps) ≤ 100,000, and both slots of a pair are valid and differentListing every row is impossible: a group of 25 different cards alone has about 1.6e+25 rows. The answer has to be counted, and it is huge, so it is given modulo 1,000,000,007. Grouping the slots takes about 100,000 union steps, and counting each group takes one pass over the 26 letters.