<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>bubble sort Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/bubble-sort/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/bubble-sort/</link>
	<description></description>
	<lastBuildDate>Wed, 08 Jul 2020 20:34:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>bubble sort Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/bubble-sort/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Jul 2020 21:56:25 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[bubble sort]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[min number]]></category>
		<category><![CDATA[reverse paris]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7035</guid>

					<description><![CDATA[<p>Given a string&#160;num&#160;representing&#160;the digits&#160;of&#160;a very large integer and an integer&#160;k. You are allowed to swap any two adjacent digits of the integer&#160;at most&#160;k&#160;times. Return&#160;the minimum&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/">花花酱 LeetCode 1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits - 刷题找工作 EP341" width="500" height="281" src="https://www.youtube.com/embed/0EgQs2WWres?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given a string&nbsp;<code>num</code>&nbsp;representing&nbsp;<strong>the digits</strong>&nbsp;of&nbsp;a very large integer and an integer&nbsp;<code>k</code>.</p>



<p>You are allowed to swap any two adjacent digits of the integer&nbsp;<strong>at most</strong>&nbsp;<code>k</code>&nbsp;times.</p>



<p>Return&nbsp;<em>the minimum integer</em>&nbsp;you can obtain also as a string.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/06/17/q4_1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "4321", k = 4
<strong>Output:</strong> "1342"
<strong>Explanation:</strong> The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "100", k = 1
<strong>Output:</strong> "010"
<strong>Explanation:</strong> It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "36789", k = 1000
<strong>Output:</strong> "36789"
<strong>Explanation:</strong> We can keep the number without any swaps.
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "22", k = 22
<strong>Output:</strong> "22"
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "9438957234785635408", k = 23
<strong>Output:</strong> "0345989723478563548"
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= num.length &lt;= 30000</code></li><li><code>num</code>&nbsp;contains&nbsp;<strong>digits</strong>&nbsp;only and doesn&#8217;t have&nbsp;<strong>leading zeros</strong>.</li><li><code>1 &lt;= k &lt;= 10^9</code></li></ul>



<h2><strong>Solution: Greedy + Recursion</strong> <strong>(Update: TLE after 7/6/2020)</strong></h2>



<p>Move the smallest number to the left and recursion on the right substring with length equals to n -= 1.</p>



<p>4321 k = 4 =&gt; 1 + solve(432, 4-3) = 1 + solve(432, 1) = 1 + 3 + solve(42, 0) = 1 + 3 + 42 = 1342.</p>



<p>Time complexity: O(n^2)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string minInteger(string num, int k) {
    const int n = num.size();
    if (k &gt;= n * (n - 1) / 2) {
      sort(begin(num), end(num));
      return num;
    }
    
    int s = 0;
    while (k &gt; 0 &amp;&amp; s &lt; n) {
      auto bit = begin(num);
      auto it = min_element(bit + s, bit + min(s + k + 1, n));
      k -= distance(bit + s, it);
      rotate(bit + (s++), it, next(it));
    }
    return num;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Binary Indexed Tree / Fenwick Tree</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-1.png" alt="" class="wp-image-7043" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-2.png" alt="" class="wp-image-7044" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-3.png" alt="" class="wp-image-7045" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/07/1505-ep341-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Moving elements in a string is a very expensive operation, basically O(n) per op. Actually, we don&#8217;t need to move the elements physically, instead we track how many elements before i has been moved to the &#8220;front&#8221;. Thus we know the cost to move the i-th element to the &#8220;front&#8221;, which is i &#8211; elements_moved_before_i or prefix_sum(0~i-1) if we mark moved element as 1.</p>



<p>We know BIT / Fenwick Tree is good for dynamic prefix sum computation which helps to reduce the time complexity to O(nlogn).</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Fenwick {
 public:
  explicit Fenwick(int n) : sums_(n + 1) {}
  
  void update(int i, int delta) {
    ++i;
    while (i &lt;  sums_.size()) {
      sums_[i] += delta;
      i += i &amp; -i;
    }
  }
  
  int query(int i) {
    ++i;
    int ans = 0;
    while (i &gt; 0) {
      ans += sums_[i];
      i -= i &amp; -i;
    }
    return ans;
  }
 private:
  vector&lt;int&gt; sums_;
};

class Solution {
public:
  string minInteger(string num, int k) {    
    const int n = num.length();
    vector&lt;queue&lt;int&gt;&gt; pos(10);
    for (int i = 0; i &lt; n; ++i)
      pos[num[i] - '0'].push(i);    
    
    Fenwick tree(n);
    vector&lt;int&gt; used(n);
    string ans;
    while (k &gt; 0 &amp; ans.length() &lt; n) {      
      for (int d = 0; d &lt; 10; ++d) {
        if (pos[d].empty()) continue;
        const int i = pos[d].front();
        const int cost = i - tree.query(i - 1);
        if (cost &gt; k) continue;        
        k -= cost;
        ans += ('0' + d);
        tree.update(i, 1);
        used[i] = true;
        pos[d].pop();
        break;
      }
    };
    
    for (int i = 0; i &lt; n; ++i)
      if (!used[i]) ans += num[i];
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  class Fenwick {
    private int[] sums;
    
    public Fenwick(int n) {
      this.sums = new int[n + 1];
    }
    
    public void update(int i, int delta) {
      ++i;
      while (i &lt; sums.length) {
        this.sums[i] += delta;
        i += i &amp; -i;
      }
    }
    
    public int query(int i) {
      int ans = 0;
      ++i;
      while (i &gt; 0) {
        ans += this.sums[i];
        i -= i &amp; -i;
      }
      return ans;
    }
  }
  
  public String minInteger(String num, int k) {
    int n = num.length();
    var used = new boolean[n];
    var pos = new ArrayList&lt;ArrayDeque&lt;Integer&gt;&gt;();
    for (int i = 0; i &lt;= 9; ++i)
      pos.add(new ArrayDeque&lt;Integer&gt;());    
    for (int i = 0; i &lt; num.length(); ++i)
      pos.get(num.charAt(i) - '0').offer(i);
    var tree = new Fenwick(n);
    var sb = new StringBuilder();
    while (k &gt; 0 &amp;&amp; sb.length() &lt; n) {
      for (int d = 0; d &lt;= 9; ++d) {
        Integer i = pos.get(d).peek();
        if (i == null) continue;
        int cost = i - tree.query(i - 1);
        if (cost &gt; k) continue;        
        sb.append((char)(d + '0'));
        k -= cost;
        pos.get(d).removeFirst();
        tree.update(i, 1);
        used[i] = true;
        break;
      }
    }
    for (int i = 0; i &lt; n; ++i)
      if (!used[i]) sb.append(num.charAt(i));
    return sb.toString();
  }
}</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Fenwick:
  def __init__(self, n):
    self.sums = [0] * (n + 1)
  
  def query(self, i):
    ans = 0
    i += 1
    while i &gt; 0:
      ans += self.sums[i];
      i -= i &amp; -i
    return ans
  
  def update(self, i, delta):
    i += 1
    while i &lt; len(self.sums):
      self.sums[i] += delta
      i += i &amp; -i


class Solution:
  def minInteger(self, num: str, k: int) -&gt; str:    
    n = len(num)
    used = [False] * n
    pos = [deque() for _ in range(10)]
    for i, c in enumerate(num):
      pos[ord(c) - ord(&quot;0&quot;)].append(i)
    tree = Fenwick(n)
    ans = []
    while k &gt; 0 and len(ans) &lt; n:
      for d in range(10):
        if not pos[d]: continue
        i = pos[d][0]
        cost = i - tree.query(i - 1)
        if cost &gt; k: continue
        k -= cost
        ans.append(chr(d + ord(&quot;0&quot;)))
        tree.update(i, 1)
        used[i] = True
        pos[d].popleft()
        break
    for i in range(n):
      if not used[i]: ans.append(num[i])
    return &quot;&quot;.join(ans)</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/">花花酱 LeetCode 1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
