Swap Lex Order
Last updated
Last updated
Given a string str
and array of pairs
that indicates which indices in the string can be swapped, return the string that results from doing the allowed swaps. You can swap indices any number of times.
Example
For str = "abdc"
and pairs = [[1, 4], [3, 4]]
, the output should be
solution(str, pairs) = "dbca"
.
By swapping the given indices, you get the strings: "cbda"
, "cbad"
, "dbac"
, "dbca"
. The lexicographically largest string in this list is "dbca"
.
Construct tree for pairs and find connect component to know which indexes can be freely swapped (Ex: 1,4,3 are connected, so any sequence: 143, 134, 341, 314 .... is valid). Each connected component is free to swap and not interfere with each other (Ex: 1,4 and 7,8,9 means 1,4 can freely swap and 7,8,9 can freely swap, but nothing in 1,4 can appear in 7,8,9)
Find the largest lex order of the corresponding connected component (Ex: for 1,4,3-->a,d,c so the largest lex order is dca, which correspond to 431)
Replace the corresponding order to the original string (Ex: original: abdc-->1234, new sequence is 431-->dbca, b is index 2, cannot change)
TreeSet is different from HashSet that TreeSet remain a natural order: set{1,4,3} appears to be {1,3,4} for TreeSet while remain unordered for HashSet