{"id":5573,"date":"2019-09-22T02:18:15","date_gmt":"2019-09-22T09:18:15","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=5573"},"modified":"2019-09-25T23:13:45","modified_gmt":"2019-09-26T06:13:45","slug":"leetcode-1202-smallest-string-with-swaps","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-1202-smallest-string-with-swaps\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 1202. Smallest String With Swaps"},"content":{"rendered":"\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 1202. Smallest String With Swaps - \u5237\u9898\u627e\u5de5\u4f5c EP271\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/qosJ4632QAg?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p>You are given a string&nbsp;<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>\n\n\n\n<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>\n\n\n\n<p>Return the&nbsp;lexicographically smallest string that&nbsp;<code>s<\/code>&nbsp;can be changed to after using the swaps.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> s = \"dcab\", pairs = [[0,3],[1,2]]\n<strong>Output:<\/strong> \"bacd\"\n<strong>Explaination:<\/strong> \nSwap s[0] and s[3], s = \"bcad\"\nSwap s[1] and s[2], s = \"bacd\"\n<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> s = \"dcab\", pairs = [[0,3],[1,2],[0,2]]\n<strong>Output:<\/strong> \"abcd\"\n<strong>Explaination: <\/strong>\nSwap s[0] and s[3], s = \"bcad\"\nSwap s[0] and s[2], s = \"acbd\"\nSwap s[1] and s[2], s = \"abcd\"<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> s = \"cba\", pairs = [[0,1],[1,2]]\n<strong>Output:<\/strong> \"abc\"\n<strong>Explaination: <\/strong>\nSwap s[0] and s[1], s = \"bca\"\nSwap s[1] and s[2], s = \"bac\"\nSwap s[0] and s[1], s = \"abc\"\n\n<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><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>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Solution: Connected Components<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"960\" height=\"540\" src=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2019\/09\/1202-ep271.png\" alt=\"\" class=\"wp-image-5587\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2019\/09\/1202-ep271.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2019\/09\/1202-ep271-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2019\/09\/1202-ep271-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/figure>\n\n\n\n<p>Use DFS \/ Union-Find to find all the connected components of swapable indices. For each connected components (index group), extract the subsequence of corresponding chars as a string, sort it and put it back to the original string in the same location.<\/p>\n\n\n\n<p>e.g. s = &#8220;dcab&#8221;, pairs = [[0,3],[1,2]]<br>There are two connected components: {0,3}, {1,2}<br>subsequences: <br>1. 0,3 &#8220;db&#8221;, sorted: &#8220;bd&#8221;<br>2. 1,2 &#8220;ca&#8221;, sorted: &#8220;ac&#8221;<br>0 =&gt; b<br>1 =&gt; a<br>2 =&gt; c<br>3 =&gt; d<br>final = &#8220;bacd&#8221;<br><\/p>\n\n\n\n<p>Time complexity: DFS: O(nlogn + k*(V+E)), Union-Find: O(nlogn + V+E)<br>Space complexity: O(n)<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++\/DFS<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"C++\">\n\/\/ Author: Huahua, 268 ms, 89 MB\nclass Solution {\npublic:\n  string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {\n    vector<vector<int>> g(s.length());\n    for (const auto& e : pairs) {\n      g[e[0]].push_back(e[1]);\n      g[e[1]].push_back(e[0]);\n    }\n\n    unordered_set<int> seen;\n    vector<int> idx;\n    string tmp;\n    function<void(int)> dfs = [&](int cur) {\n      if (seen.count(cur)) return;\n      seen.insert(cur);\n      idx.push_back(cur);\n      tmp += s[cur];\n      for (int nxt : g[cur]) dfs(nxt);\n    };\n\n    for (int i = 0; i < s.length(); ++i) {\n      if (seen.count(i)) continue;\n      idx.clear();\n      tmp.clear();\n      dfs(i);\n      sort(begin(tmp), end(tmp));\n      sort(begin(idx), end(idx));      \n      for (int k = 0; k < idx.size(); ++k)\n        s[idx[k]] = tmp[k];\n    }\n    return s;\n  }\n};\n<\/pre>\n\n<\/div><h2 class=\"tabtitle\">C++\/Union-Find<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"c++\">\n\/\/ Author: Huahua, 152 ms, 48.2 MB\nclass Solution {\npublic:\n  string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {\n    int n = s.length();\n    vector<int> p(n);    \n    iota(begin(p), end(p), 0); \/\/ p = {0, 1, 2, ... n - 1}\n    \n    function<int(int)> find = [&](int x) {\n      return p[x] == x ? x : p[x] = find(p[x]);\n    };        \n    \n    for (const auto& e : pairs)\n      p[find(e[0])] = find(e[1]); \/\/ union\n    \n    vector<vector<int>> idx(n);\n    vector<string> ss(n);\n    \n    for (int i = 0; i < s.length(); ++i) {\n      int id = find(i);      \n      idx[id].push_back(i); \/\/ already sorted\n      ss[id].push_back(s[i]);\n    }\n    \n    for (int i = 0; i < n; ++i) {      \n      sort(begin(ss[i]), end(ss[i]));\n      for (int k = 0; k < idx[i].size(); ++k)\n        s[idx[i][k]] = ss[i][k];\n    }\n    \n    return s;\n  }\n};\n<\/pre>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>You are given a string&nbsp;s, and an array of pairs of indices in the string&nbsp;pairs&nbsp;where&nbsp;pairs[i] =&nbsp;[a, b]&nbsp;indicates 2 indices(0-indexed) of the string. You can&nbsp;swap the&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76],"tags":[102,33,77,177,113],"class_list":["post-5573","post","type-post","status-publish","format-standard","hentry","category-graph","tag-connected-components","tag-dfs","tag-graph","tag-medium","tag-union-find","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/5573","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=5573"}],"version-history":[{"count":7,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/5573\/revisions"}],"predecessor-version":[{"id":5588,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/5573\/revisions\/5588"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=5573"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=5573"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=5573"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}