<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>String on Yosgi</title><link>https://yosgi.github.io/en/tags/string/</link><description>Recent content in String on Yosgi</description><generator>Hugo</generator><language>en</language><lastBuildDate>Mon, 29 Jun 2026 09:20:51 +0000</lastBuildDate><atom:link href="https://yosgi.github.io/en/tags/string/index.xml" rel="self" type="application/rss+xml"/><item><title>1202-Swap elements in a string</title><link>https://yosgi.github.io/en/post/1202-swap-elements-in-a-string/</link><pubDate>Tue, 06 Jul 2021 00:00:00 +1200</pubDate><guid>https://yosgi.github.io/en/post/1202-swap-elements-in-a-string/</guid><description>It is mainly used for learning and checking ideas, and you will start only after looking at the answers. The idea is to group the interchangeable strings first, sort the groups, and then combine them Union-find is to use recursion or while loop to implement find, and then use arrays and subscripts to implement union var smallestStringWithSwaps = function(s, pairs) { var fa = [] var find = function (x) { if (x === fa[x]) { return x } else { return fa[x] = find(fa[x]) } } for (let i = 0; i &lt; s.length; i++) { fa[i] = i } for(let i = 0 ; i &lt; pairs.length ; i ++) { const [x,y] = pairs[i] fa[find(x)] = find(y) } var n = s.length // Calculate the grouped map const vec = new Array(n).fill(0).map(() =&gt; new Array()); for (let i = 0; i &lt; n; i++) { fa[i] = find(i); vec[fa[i]].push(s[i]); } console.log(fa) // Sort the grouped map for (let i = 0; i &lt; n; ++i) { if (vec[i].length &gt; 0) { vec[i].sort((a, b) =&gt; a.charCodeAt() - b.charCodeAt()); } } // Combined into ans const ans = new Array(n).fill(0); for (let i = 0; i &lt; n; ++i) { var group = fa[i] if ( group!= undefined &amp;&amp; vec[group].length) { // Take out the smallest number in each group ans[i] = vec[fa[i]].shift() } else { ans[i] = s[i] } } return ans.join('') };It is mainly used to learn and check the ideas, and you will start only after looking at the answers.</description></item></channel></rss>