Problem 596853 · medium · Level 05 Advanced Algorithms & Graphs

Rearranging Letters on Linked Hooks

union-find · strings · sorting within groups

A shop sign hangs its letters s on a row of hooks. Some pairs of hooks, listed in pairs as [i, j], are joined by a rail, so the letters on hooks i and j can trade places, as often as you like and in any order. Return the alphabetically earliest sign you can end up with.

Examples

Input:  s = "garden", pairs = [[0, 4], [4, 5], [1, 3]]
Output: "eardgn"
Explanation: positions {0, 4, 5} hold g, e and n; positions {1, 3} hold a and d; position 2 is on its own. Each group is sorted independently.

Input:  s = "garden", pairs = [[0, 4], [4, 5], [1, 3], [2, 3]]
Output: "eadrgn"
Explanation: the extra rail joins position 2 to the group {1, 3}, so a, r and d can be sorted together.

Input:  s = "tea", pairs = []
Output: "tea"

Constraints

  • 0 <= len(s) <= 10**4, 0 <= len(pairs) <= 2 * 10**4, lowercase letters only
  • Target: O((n + P) * alpha(n) + n log n) time.

Goals

  • Realise that swappable positions form groups that can be permuted freely
  • Sort the characters of each group and write them back in position order
Starting Python…