-
Notifications
You must be signed in to change notification settings - Fork 161
/
smallest-string-with-swaps.md
47 lines (37 loc) · 1.68 KB
/
smallest-string-with-swaps.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<p>You are given a string <code>s</code>, and an array of pairs of indices in the string <code>pairs</code> where <code>pairs[i] = [a, b]</code> indicates 2 indices(0-indexed) of the string.</p>
<p>You can swap the characters at any pair of indices in the given <code>pairs</code> <strong>any number of times</strong>.</p>
<p>Return the lexicographically smallest string that <code>s</code> can be changed to after using the swaps.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "dcab", pairs = [[0,3],[1,2]]
<strong>Output:</strong> "bacd"
<strong>Explaination:</strong>
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "dcab", pairs = [[0,3],[1,2],[0,2]]
<strong>Output:</strong> "abcd"
<strong>Explaination: </strong>
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"</pre>
<p><strong>Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "cba", pairs = [[0,1],[1,2]]
<strong>Output:</strong> "abc"
<strong>Explaination: </strong>
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10^5</code></li>
<li><code>0 <= pairs.length <= 10^5</code></li>
<li><code>0 <= pairs[i][0], pairs[i][1] < s.length</code></li>
<li><code>s</code> only contains lower case English letters.</li>
</ul>