<p>You are given a string <code>s</code>, and an array of pairs of indices in the string&nbsp;<code>pairs</code>&nbsp;where&nbsp;<code>pairs[i] =&nbsp;[a, b]</code>&nbsp;indicates 2 indices(0-indexed) of the string.</p>

<p>You can&nbsp;swap the characters at any pair of indices in the given&nbsp;<code>pairs</code>&nbsp;<strong>any number of times</strong>.</p>

<p>Return the&nbsp;lexicographically smallest string that <code>s</code>&nbsp;can be changed to after using the swaps.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;dcab&quot;, pairs = [[0,3],[1,2]]
<strong>Output:</strong> &quot;bacd&quot;
<strong>Explaination:</strong> 
Swap s[0] and s[3], s = &quot;bcad&quot;
Swap s[1] and s[2], s = &quot;bacd&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;dcab&quot;, pairs = [[0,3],[1,2],[0,2]]
<strong>Output:</strong> &quot;abcd&quot;
<strong>Explaination: </strong>
Swap s[0] and s[3], s = &quot;bcad&quot;
Swap s[0] and s[2], s = &quot;acbd&quot;
Swap s[1] and s[2], s = &quot;abcd&quot;</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;cba&quot;, pairs = [[0,1],[1,2]]
<strong>Output:</strong> &quot;abc&quot;
<strong>Explaination: </strong>
Swap s[0] and s[1], s = &quot;bca&quot;
Swap s[1] and s[2], s = &quot;bac&quot;
Swap s[0] and s[1], s = &quot;abc&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10^5</code></li>
	<li><code>0 &lt;= pairs.length &lt;= 10^5</code></li>
	<li><code>0 &lt;= pairs[i][0], pairs[i][1] &lt;&nbsp;s.length</code></li>
	<li><code>s</code>&nbsp;only contains lower case English letters.</li>
</ul>

# 2024/09/03
# 刷Uber高频题目
# 
# 有意思这题
# 感觉不能用greedy，单次导致远离最小，可能是为了之后的操作铺路
# 是这样吗？
# 想用DFS，但必须要剪枝，或者提供方向才行
# DP？好像可以，example1和2有点像
# 不对，看example3可知
# 感觉应该是greedy，n = len(pairs)，不断iterate pairs，看是否有swap能实现更小，知道不行
# 问题是怎么证明
# 写了一下，发现不对，看答案去了
class Solution:
    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
        chars = list(s)

        while True:
            flag = False
            for x, y in pairs:
                if ord(chars[x]) > ord(chars[y]):
                    chars[x], chars[y] = chars[y], chars[x]
                    flag = True
            
            if not flag:
                break

        return "".join(chars)
# approach1 DFS
# 第一步还是构建graph，最重要的一点来了:
# The important point to note here is that if we have pairs like (a, b) and (b, c), then we can swap characters at indices a and c
# 这是能想到是graph的关键，即具有传递性
# If a pair of vertices exists on the same path, then they can be swapped by repeatedly swapping with other vertices in the path between them.
# step1:
# we can rearrange the characters such that any character is at any index within the connected component.
# step2:
# To find the lexicographically smallest string, we need to sort the characters that correspond to these indices in ascending order 
# 或者分得更细:
# 1. build a graph using the given pairs
# 2. find the connected components in the graph
# 3. sort the characters in each connected component in ascending order
# 4. and build the smallest string.
# 不看代码了，自己写一下
class Solution:
    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
        n = len(s)
        graph = defaultdict(list)

        for x, y in pairs:
            graph[x].append(y)
            graph[y].append(x)

        groups = []
        visited = set()
        for i in range(n):
            if i in visited:
                continue
            if i in graph:
                group = set()
                group.add(i)
                self.dfs(graph, i, group)
                visited.update(group)
                groups.append(list(sorted(list(group))))
        
        result = [None] * n
        for group in groups:
            cands = [s[i] for i in group]
            cands.sort()
            for i, char in zip(group, cands):
                result[i] = char

        for i in range(n):
            if result[i] == None:
                result[i] = s[i]

        return "".join(result)



    def dfs(self, graph, node, group):
        for nei in graph[node]:
            if nei in group:
                continue
            group.add(nei)
            self.dfs(graph, nei, group)














57130