Skip to content

Commit 1df67b5

Browse files
Create smallest_string_with_swaps.py
1 parent ec35750 commit 1df67b5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

smallest_string_with_swaps.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
3+
def dfs(node, subgraph):
4+
if node not in seen:
5+
seen.add(node)
6+
subgraph.append(node)
7+
for neighbor in graph[node]:
8+
dfs(neighbor, subgraph)
9+
10+
seen = set()
11+
graph = defaultdict(list)
12+
for src, dest in pairs:
13+
graph[src].append(dest)
14+
graph[dest].append(src)
15+
16+
res = list(s)
17+
for node in graph.keys():
18+
if len(seen) == len(res):
19+
return ''.join(res)
20+
21+
sub_graph = []
22+
dfs(node, sub_graph)
23+
24+
if len(sub_graph) != 0:
25+
sub_graph = sorted(list(set(sub_graph)))
26+
sub_char = sorted([s[i] for i in sub_graph])
27+
28+
for x, y in zip(sub_graph, sub_char):
29+
res[x] = y
30+
31+
return ''.join(res)

0 commit comments

Comments
 (0)