<?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>kth Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/kth/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/kth/</link>
	<description></description>
	<lastBuildDate>Wed, 06 May 2020 05:31:19 +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>kth Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/kth/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 06 May 2020 05:28:26 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[kth]]></category>
		<category><![CDATA[priority queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6709</guid>

					<description><![CDATA[<p>You are given an&#160;m&#160;* n&#160;matrix,&#160;mat, and an integer&#160;k,&#160;which&#160;has its rows sorted in non-decreasing&#160;order. You are allowed to choose exactly 1 element from each row to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/">花花酱 LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an&nbsp;<code>m&nbsp;* n</code>&nbsp;matrix,&nbsp;<code>mat</code>, and an integer&nbsp;<code>k</code>,&nbsp;which&nbsp;has its rows sorted in non-decreasing&nbsp;order.</p>



<p>You are allowed to choose exactly 1 element from each row to form an array.&nbsp;Return the Kth&nbsp;<strong>smallest</strong>&nbsp;array sum among all possible arrays.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,3,11],[2,4,6]], k = 5
<strong>Output:</strong> 7
<strong>Explanation: </strong>Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.  </pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,3,11],[2,4,6]], k = 9
<strong>Output:</strong> 17
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
<strong>Output:</strong> 9
<strong>Explanation:</strong> Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.  
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,1,10],[2,2,9]], k = 7
<strong>Output:</strong> 12
</pre>



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



<ul><li><code>m == mat.length</code></li><li><code>n == mat.length[i]</code></li><li><code>1 &lt;= m, n &lt;= 40</code></li><li><code>1 &lt;= k &lt;= min(200, n ^&nbsp;m)</code></li><li><code>1 &lt;= mat[i][j] &lt;= 5000</code></li><li><code>mat[i]</code>&nbsp;is a non decreasing array.</li></ul>



<h2><strong>Solution 1: Priority Queue</strong></h2>



<p>Generate the arrays in order.</p>



<p>Each node is {sum, idx_0, idx_1, &#8230;, idx_m},</p>



<p>Start with {sum_0, 0, 0, &#8230;, 0}.</p>



<p>For expansion, pick one row and increase its index</p>



<p>Time complexity: O(k * m ^ 2* log k)<br>Space complexity: O(k)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int kthSmallest(vector&lt;vector&lt;int&gt;&gt;&amp; mat, int k) {
    const int m = mat.size();
    const int n = mat[0].size();
    priority_queue&lt;vector&lt;int&gt;&gt; q;
    vector&lt;int&gt; node(m + 1); // {-sum, idx_0, idx_1, ..., idx_m}
    for (int i = 0; i &lt; m; ++i) node[0] -= mat[i][0];
    q.push(node);
    set&lt;vector&lt;int&gt;&gt; seen{{node}};
    while (!q.empty()) {
      const vector&lt;int&gt; cur = q.top(); q.pop();
      if (--k == 0) return -cur[0];  
      for (int i = 1; i &lt;= m; ++i) {
        if (cur[i] == n - 1) continue;
        vector&lt;int&gt; nxt(cur);
        ++nxt[i]; // increase i-th row's index.
        // Update sum.
        nxt[0] -= (mat[i - 1][nxt[i]] - mat[i - 1][nxt[i] - 1]);
        if (!seen.insert(nxt).second) continue;      
        q.push(move(nxt));
      }
    }
    return -1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/">花花酱 LeetCode 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows</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/searching/leetcode-1439-find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 230. Kth Smallest Element in a BST</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-230-kth-smallest-element-in-a-bst/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-230-kth-smallest-element-in-a-bst/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 13 Apr 2019 07:36:05 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[kth]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5060</guid>

					<description><![CDATA[<p>Given a binary search tree, write a function&#160;kthSmallest&#160;to find the&#160;kth smallest element in it. Note:&#160;You may assume k is always valid, 1 ≤ k ≤&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-230-kth-smallest-element-in-a-bst/">花花酱 LeetCode 230. Kth Smallest Element in a BST</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a binary search tree, write a function&nbsp;<code>kthSmallest</code>&nbsp;to find the&nbsp;<strong>k</strong>th smallest element in it.</p>



<p><strong>Note:&nbsp;</strong><br>You may assume k is always valid, 1 ≤ k ≤ BST&#8217;s total elements.</p>



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



<pre class="wp-block-preformatted; crayon:false"><strong>Input:</strong> root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
&nbsp;  2
<strong>Output:</strong> 1</pre>



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



<pre class="wp-block-preformatted; crayon:false"><strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
<strong>Output:</strong> 3
</pre>



<p><strong>Follow up:</strong><br>What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?</p>



<p>Solution: Inorder traversal</p>



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



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

<pre class="crayon-plain-tag">class Solution {
public:
  int kthSmallest(TreeNode* root, int k) {
    return inorder(root, k);
  }
private:
  int inorder(TreeNode* root, int&amp; k) {
    if (!root) return -1;
    int x = inorder(root-&gt;left, k);
    if (k == 0) return x;
    if (--k == 0) return root-&gt;val;
    return inorder(root-&gt;right, k);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-230-kth-smallest-element-in-a-bst/">花花酱 LeetCode 230. Kth Smallest Element in a BST</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/tree/leetcode-230-kth-smallest-element-in-a-bst/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 668. Kth Smallest Number in Multiplication Table</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-668-kth-smallest-number-in-multiplication-table/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-668-kth-smallest-number-in-multiplication-table/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 10 Sep 2018 10:16:04 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[kth]]></category>
		<category><![CDATA[matrix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3898</guid>

					<description><![CDATA[<p>Problem Nearly every one have used the Multiplication Table. But could you find out the k-th smallest number quickly from the multiplication table? Given the height m and the length n of&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-668-kth-smallest-number-in-multiplication-table/">花花酱 LeetCode 668. Kth Smallest Number in Multiplication Table</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/qvtYRm4reL4?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Nearly every one have used the <a href="https://en.wikipedia.org/wiki/Multiplication_table">Multiplication Table</a>. But could you find out the <code>k-th</code> smallest number quickly from the multiplication table?</p>
<p>Given the height <code>m</code> and the length <code>n</code> of a <code>m * n</code> Multiplication Table, and a positive integer <code>k</code>, you need to return the <code>k-th</code> smallest number in this table.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> m = 3, n = 3, k = 5
<b>Output:</b> 
<b>Explanation:</b> 
The Multiplication Table:
1	2	3
2	4	6
3	6	9

The 5-th smallest number is 3 (1, 2, 2, 3, 3).
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b> m = 2, n = 3, k = 6
<b>Output:</b> 
<b>Explanation:</b> 
The Multiplication Table:
1	2	3
2	4	6

The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6).
</pre>
<p><b>Note:</b></p>
<ol>
<li>The <code>m</code> and <code>n</code> will be in the range [1, 30000].</li>
<li>The <code>k</code> will be in the range [1, m * n]</li>
</ol>
<p><img class="alignnone size-full wp-image-3903" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/09/668-ep223.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/09/668-ep223.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/09/668-ep223-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/09/668-ep223-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"> </ins></p>
<h1><strong>Solution 1: Nth element (MLE)</strong></h1>
<p>Time complexity: O(mn)</p>
<p>Space complexity: O(mn)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// 59 / 69 test cases passed.
class Solution {
public:
  int findKthNumber(int m, int n, int k) {
    vector&lt;int&gt; s(m * n);
    auto it = begin(s);
    for (int i = 1; i &lt;= m; ++i)
      for (int j = 1; j &lt;= n; ++j)
        *it++ = i * j;
    nth_element(begin(s), begin(s) + k - 1, end(s));
    return s[k - 1];
  }
};</pre><p></div></div></p>
<h1><strong>Solution2 : Binary Search</strong></h1>
<p>Find first x such that there are k elements less or equal to x in the table.</p>
<p>Time complexity: O(m*log(m*n))</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 12 ms
class Solution {
public:
  int findKthNumber(int m, int n, int k) {
    int l = 1;
    int r = m * n + 1;
    while (l &lt; r) {
      int x = l + (r - l) / 2;
      if (LEX(m, n, x) &gt;= k)
        r = x;
      else
        l = x + 1;
    }
    return l;
  }
private:
  // Returns # of elements in the m*n table that are &lt;= x
  int LEX(int m, int n, int x) {
    int count = 0;
    for (int i = 1; i &lt;= m; ++i)
      count += min(n, x / i);
    return count;
  }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 16 ms
class Solution {
  public int findKthNumber(int m, int n, int k) {
    int l = 1;
    int r = m * n + 1;
    while (l &lt; r) {
      int x = l + (r - l) / 2;
      if (LEX(m, n, x) &gt;= k)
        r = x;
      else
        l = x + 1;
    }
    return l;
  }

  // Returns # of elements in the m*n table that are &lt;= x
  private int LEX(int m, int n, int x) {
    int count = 0;
    for (int i = 1; i &lt;= m; ++i)
      count += Math.min(n, x / i);
    return count;
  }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua, 976 ms
class Solution:
  def findKthNumber(self, m, n, k):
    def LEX(m, n, x, k):
      count = 0
      for i in range(1, min(m + 1, x + 1)):
        count += min(n, x // i)
        if count &gt;= k: return count
      return count
    l = 1
    r = m * n + 1
    while l &lt; r:
      x = l + (r - l) // 2
      if LEX(m, n, x, k) &gt;= k:
        r = x
      else:
        l = x + 1
    return l</pre><p></div></div></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-378-kth-smallest-element-in-a-sorted-matrix/">花花酱 LeetCode 378. Kth Smallest Element in a Sorted Matrix</a></li>
<li><a href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-786-k-th-smallest-prime-fraction/">花花酱 LeetCode 786. K-th Smallest Prime Fraction</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-668-kth-smallest-number-in-multiplication-table/">花花酱 LeetCode 668. Kth Smallest Number in Multiplication Table</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/algorithms/binary-search/leetcode-668-kth-smallest-number-in-multiplication-table/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 378. Kth Smallest Element in a Sorted Matrix</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-378-kth-smallest-element-in-a-sorted-matrix/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-378-kth-smallest-element-in-a-sorted-matrix/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 21 Feb 2018 02:22:22 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[kth]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1822</guid>

					<description><![CDATA[<p>题目大意：给你一个矩阵，每行每列各自排序。找出矩阵中第K小的元素。 Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-378-kth-smallest-element-in-a-sorted-matrix/">花花酱 LeetCode 378. Kth Smallest Element in a Sorted Matrix</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>题目大意：给你一个矩阵，每行每列各自排序。找出矩阵中第K小的元素。</p>
<p>Given a <i>n</i> x <i>n</i> matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.</p>
<p>Note that it is the kth smallest element in the sorted order, not the kth distinct element.</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.</pre><p><b>Note: </b><br />
You may assume k is always valid, 1 ≤ k ≤ n<sup>2</sup>.</p>
<h1><strong>Solution 1: Binary Search</strong></h1>
<p>Find the smallest x, such that there are k elements that are smaller or equal to x.</p>
<p>Time complexity: O(nlogn*log(max &#8211; min))</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 24 ms (beats 97.12%)
class Solution {
public:
  int kthSmallest(vector&lt;vector&lt;int&gt;&gt;&amp; matrix, int k) {
    const int n = matrix.size();
    long l = matrix[0][0];
    long r = matrix[n - 1][n - 1] + 1;
    while (l &lt; r) {
      long m = l + (r - l) / 2;      
      int total = 0;
      int s = n;
      for (const auto&amp; row : matrix)
        total += (s = distance(begin(row), upper_bound(begin(row), begin(row) + s, m)));
      if (total &gt;= k)
        r = m;
      else
        l = m + 1;
    }
    return l;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-378-kth-smallest-element-in-a-sorted-matrix/">花花酱 LeetCode 378. Kth Smallest Element in a Sorted Matrix</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/algorithms/binary-search/leetcode-378-kth-smallest-element-in-a-sorted-matrix/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
