<?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>partition &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/partition/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Sun, 13 Apr 2025 03:01:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>partition &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2161. Partition Array According to Given Pivot</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2161-partition-array-according-to-given-pivot/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2161-partition-array-according-to-given-pivot/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Apr 2025 03:01:02 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[partition]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10348</guid>

					<description><![CDATA[最直接的方法就是扫描三遍，&#60;, = , > pivot。 时间复杂度：O(n)空间复杂度：O(1) // no extra space used except for output [crayon-68002900a8f74406509207/]]]></description>
										<content:encoded><![CDATA[
<p>最直接的方法就是扫描三遍，&lt;, = , > pivot。</p>



<p>时间复杂度：O(n)<br>空间复杂度：O(1) // no extra space used except for output</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  vector&lt;int&gt; pivotArray(vector&lt;int&gt;&amp; nums, int pivot) {
    vector&lt;int&gt; ans;
    for (int x: nums)
      if (x &lt; pivot) ans.push_back(x);
    for (int x : nums)
      if (x == pivot) ans.push_back(x);
    for (int x : nums)
      if (x &gt; pivot) ans.push_back(x);
    return ans;
  }
};</pre>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2161-partition-array-according-to-given-pivot/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1278. Palindrome Partitioning III</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1278-palindrome-partitioning-iii/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1278-palindrome-partitioning-iii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 02 Dec 2019 08:09:16 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[k groups]]></category>
		<category><![CDATA[partition]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5915</guid>

					<description><![CDATA[You are given a string&#160;s&#160;containing lowercase letters and an integer&#160;k. You need to : First, change some characters of&#160;s&#160;to other lowercase English letters. Then divide&#160;s&#160;into&#160;k&#160;non-empty&#8230;]]></description>
										<content:encoded><![CDATA[
<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">
<iframe title="花花酱 LeetCode 1278. Palindrome Partitioning III - 刷题找工作 EP280" width="500" height="375" src="https://www.youtube.com/embed/kD6ShM6jr3g?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>
</div></figure>



<p>You are given a string&nbsp;<code>s</code>&nbsp;containing lowercase letters and an integer&nbsp;<code>k</code>. You need to :</p>



<ul class="wp-block-list"><li>First, change some characters of&nbsp;<code>s</code>&nbsp;to other lowercase English letters.</li><li>Then divide&nbsp;<code>s</code>&nbsp;into&nbsp;<code>k</code>&nbsp;non-empty disjoint substrings such that each substring is palindrome.</li></ul>



<p>Return the minimal number of characters that you need to change&nbsp;to divide the string.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abc", k = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong>&nbsp;You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aabbc", k = 3
<strong>Output:</strong> 0
<strong>Explanation:</strong>&nbsp;You can split the string into "aa", "bb" and "c", all of them are palindrome.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "leetcode", k = 8
<strong>Output:</strong> 0
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= k &lt;= s.length &lt;= 100</code>.</li><li><code>s</code>&nbsp;only contains lowercase English letters.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: DP</strong></h2>



<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1278-ep280.png" alt="" class="wp-image-5921" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1278-ep280.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1278-ep280-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1278-ep280-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>dp[i][k] := min changes to make s[0~i] into k palindromes<br>dp[i][k] = min(dp[j][k &#8211; 1] + cost(j + 1, i))  0 &lt;= j &lt; i</p>



<p>ans = dp[n-1][K]</p>



<p>Time complexity: O(n^2 * K) = O(n^3)<br>Space complexity: O(n*n + n*K) = O(n^2)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua, 8 ms, 9.1 MB
class Solution {
public:
  int palindromePartition(string s, int K) {
    const int n = s.length();
    auto minChange = [&amp;](int i, int j) {
      int c = 0;
      while (i &lt; j) 
        if (s[i++] != s[j--]) ++c;      
      return c;
    };
    vector&lt;vector&lt;int&gt;&gt; cost(n, vector&lt;int&gt;(n));
    for (int i = 0; i &lt; n; ++i)
      for (int j = i + 1; j &lt; n; ++j)
        cost[i][j] = minChange(i, j);

    // dp[i][j] := min changes to make s[0~i] into k palindromes
    vector&lt;vector&lt;int&gt;&gt; dp(n, vector&lt;int&gt;(K + 1, INT_MAX / 2));
    for (int i = 0; i &lt; n; ++i) {      
      dp[i][1] = cost[0][i];
      for (int k = 1; k &lt;= K; ++k)
        for (int j = 0; j &lt; i; ++j)
          dp[i][k] = min(dp[i][k], dp[j][k - 1] + cost[j + 1][i]);        
    }
    return dp[n - 1][K];
  }
};</pre>
</div></div>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua, 4 ms, 9.1MB
class Solution {
public:
  int palindromePartition(string s, int K) {
    const int n = s.length();    
    vector&lt;vector&lt;int&gt;&gt; cost(n, vector&lt;int&gt;(n));
    for (int l = 2; l &lt;= n; ++l)
      for (int i = 0, j = l - 1; j &lt; n; ++i, ++j)
        cost[i][j] = (s[i] != s[j]) + cost[i + 1][j - 1];
    
    vector&lt;vector&lt;int&gt;&gt; dp(n, vector&lt;int&gt;(K + 1, INT_MAX / 2));
    for (int i = 0; i &lt; n; ++i) {      
      dp[i][1] = cost[0][i];
      for (int k = 2; k &lt;= K; ++k)
        for (int j = 0; j &lt; i; ++j)
          dp[i][k] = min(dp[i][k], dp[j][k - 1] + cost[j + 1][i]);        
    }
    return dp[n - 1][K];
  }
};</pre>
</div></div>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
import functools
class Solution:
  def palindromePartition(self, s: str, K: int) -&gt; int:
    @functools.lru_cache(None)
    def cost(i: int, j: int) -&gt; int:
      if i &gt;= j: return 0
      return cost(i + 1, j - 1) + (1 if s[i] != s[j] else 0)
    
    @functools.lru_cache(None)
    def dp(i: int, k: int) -&gt; int:
      if k == 1: return cost(0, i)
      if k == i + 1: return 0
      if k &gt; i + 1: return 1**9
      return min([dp(j, k - 1) + cost(j + 1, i) for j in range(i)])        
    
    return dp(len(s) - 1, K)</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1278-palindrome-partitioning-iii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 86. Partition List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-86-partition-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-86-partition-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 30 Sep 2019 16:28:18 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[partition]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5657</guid>

					<description><![CDATA[Given a linked list and a value&#160;x, partition it such that all nodes less than&#160;x&#160;come before nodes greater than or equal to&#160;x. You should preserve&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given a linked list and a value&nbsp;<em>x</em>, partition it such that all nodes less than&nbsp;<em>x</em>&nbsp;come before nodes greater than or equal to&nbsp;<em>x</em>.</p>



<p>You should preserve the original relative order of the nodes in each of the two partitions.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = 1-&gt;4-&gt;3-&gt;2-&gt;5-&gt;2, <em>x</em> = 3
<strong>Output:</strong> 1-&gt;2-&gt;2-&gt;4-&gt;3-&gt;5</pre>



<h2 class="wp-block-heading"><strong>Solution: Two dummy heads</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* partition(ListNode* head, int x) {
    ListNode dl(0);
    ListNode dr(0);
    ListNode* l = &amp;dl;
    ListNode* r = &amp;dr;
    while (head) {
      ListNode*&amp; h = (head-&gt;val &lt; x) ? l : r;
      h = h-&gt;next = head;
      head = head-&gt;next;
    }
    r-&gt;next = nullptr; // important, to avoid loop
    l-&gt;next = dr.next;
    return dl.next;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-86-partition-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 937. Reorder Log Files</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-937-reorder-log-files/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-937-reorder-log-files/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Nov 2018 07:33:06 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[partition]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4280</guid>

					<description><![CDATA[Problem https://leetcode.com/problems/reorder-log-files/description/ You have an array of logs.  Each log is a space delimited string of words. For each log, the first word in each log&#8230;]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p><a href="https://leetcode.com/problems/reorder-log-files/description/">https://leetcode.com/problems/reorder-log-files/description/</a></p>
<p>You have an array of <code>logs</code>.  Each log is a space delimited string of words.</p>
<p>For each log, the first word in each log is an alphanumeric <em>identifier</em>.  Then, either:</p>
<ul>
<li>Each word after the identifier will consist only of lowercase letters, or;</li>
<li>Each word after the identifier will consist only of digits.</li>
</ul>
<p>We will call these two varieties of logs <em>letter-logs</em> and <em>digit-logs</em>.  It is guaranteed that each log has at least one word after its identifier.</p>
<p>Reorder the logs so that all of the letter-logs come before any digit-log.  The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties.  The digit-logs should be put in their original order.</p>
<p>Return the final order of the logs.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]</span>
<strong>Output: </strong><span id="example-output-1">["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>0 &lt;= logs.length &lt;= 100</code></li>
<li><code>3 &lt;= logs[i].length &lt;= 100</code></li>
<li><code>logs[i]</code> is guaranteed to have an identifier, and a word after the identifier.</li>
</ol>
<h1><strong>Solution: Partition + Sort</strong></h1>
<ol>
<li>partition the array such that all digit logs are after all letter logs</li>
<li>sort the letter logs part based on the log content</li>
</ol>
<p>Time complexity: O(n + aloga)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
    vector&lt;string&gt; reorderLogFiles(vector&lt;string&gt;&amp; logs) {
      auto alpha_end = std::stable_partition(begin(logs),  end(logs), 
        [](const string&amp; log){ return isalpha(log.back()); });
      std::sort(begin(logs), alpha_end, [](const string&amp; a, const string&amp; b){
        return a.substr(a.find(' ')) &lt; b.substr(b.find(' '));
      });
      return logs;
    }
};</pre><p></div></div></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-937-reorder-log-files/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 561. Array Partition I</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-561-array-partition-i/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-561-array-partition-i/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 16 Aug 2018 16:14:30 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[partition]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3550</guid>

					<description><![CDATA[Problem Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), &#8230;, (an, bn) which makes&#8230;]]></description>
										<content:encoded><![CDATA[<p><iframe title="花花酱 LeetCode 561. Array Partition I - 刷题找工作 EP8" width="500" height="375" src="https://www.youtube.com/embed/wDU72F6dhS4?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></p>
<h1>Problem</h1>
<p>Given an array of <b>2n</b> integers, your task is to group these integers into <b>n</b> pairs of integer, say (a<sub>1</sub>, b<sub>1</sub>), (a<sub>2</sub>, b<sub>2</sub>), &#8230;, (a<sub>n</sub>, b<sub>n</sub>) which makes sum of min(a<sub>i</sub>, b<sub>i</sub>) for all i from 1 to n as large as possible.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> [1,4,3,2]

<b>Output:</b> 4
<b>Explanation:</b> n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
</pre>
<p><b>Note:</b></p>
<ol>
<li><b>n</b> is a positive integer, which is in the range of [1, 10000].</li>
<li>All the integers in the array will be in the range of [-10000, 10000].</li>
</ol>
<h1><strong>Solution 1: Sorting</strong></h1>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(1)</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 52 ms
class Solution {
public:
  int arrayPairSum(vector&lt;int&gt;&amp; nums) {
    std::sort(nums.begin(), nums.end());
    int ans = 0;
    for(int i = 0; i &lt; nums.size(); i += 2)
        ans += nums[i];
    return ans;
  }
};</pre><p></p>
<h1><strong>Solution 2: HashTable</strong></h1>
<p>Time complexity: O(n + max(nums) &#8211; min(nums))</p>
<p>Space complexity: O(max(nums) &#8211; min(nums))</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 39 ms
class Solution {
public:
  int arrayPairSum(vector&lt;int&gt;&amp; nums) {
    const int max_val = *max_element(begin(nums), end(nums));
    const int min_val = *min_element(begin(nums), end(nums));
    const int offset = -min_val;
    vector&lt;int&gt; c(max_val - min_val + 1);

    for (int num : nums)
        ++c[num + offset];

    int ans = 0;
    int index = 0;

    int n = min_val;

    while (n &lt;= max_val) {
      if (c[n + offset] == 0) {
        ++n;
        continue;
      }
      ans += (++index &amp; 1) ? n : 0;
      --c[n + offset];
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-561-array-partition-i/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 886. Possible Bipartition</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-886-possible-bipartition/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-886-possible-bipartition/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Aug 2018 08:40:59 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[bipartite]]></category>
		<category><![CDATA[coloring]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[partition]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3499</guid>

					<description><![CDATA[Problem Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size. Each person may dislike some other&#8230;]]></description>
										<content:encoded><![CDATA[<p><iframe loading="lazy" title="花花酱 LeetCode 886. Possible Bipartition - 刷题找工作 EP217" width="500" height="375" src="https://www.youtube.com/embed/VlZiMD7Iby4?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></p>
<h1><strong>Problem</strong></h1>
<p>Given a set of <code>N</code> people (numbered <code>1, 2, ..., N</code>), we would like to split everyone into two groups of <strong>any</strong> size.</p>
<p>Each person may dislike some other people, and they should not go into the same group.</p>
<p>Formally, if <code>dislikes[i] = [a, b]</code>, it means it is not allowed to put the people numbered <code>a</code> and <code>b</code> into the same group.</p>
<p>Return <code>true</code> if and only if it is possible to split everyone into two groups in this way.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>N = <span id="example-input-1-1">4</span>, dislikes = <span id="example-input-1-2">[[1,2],[1,3],[2,4]]</span>
<strong>Output: </strong><span id="example-output-1">true</span>
<strong>Explanation</strong>: group1 [1,4], group2 [2,3]
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>N = <span id="example-input-2-1">3</span>, dislikes = <span id="example-input-2-2">[[1,2],[1,3],[2,3]]</span>
<strong>Output: </strong><span id="example-output-2">false</span>
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>N = <span id="example-input-3-1">5</span>, dislikes = <span id="example-input-3-2">[[1,2],[2,3],[3,4],[4,5],[1,5]]</span>
<strong>Output: </strong><span id="example-output-3">false</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>1 &lt;= N &lt;= 2000</code></li>
<li><code>0 &lt;= dislikes.length &lt;= 10000</code></li>
<li><code>1 &lt;= dislikes[i][j] &lt;= N</code></li>
<li><code>dislikes[i][0] &lt; dislikes[i][1]</code></li>
<li>There does not exist <code>i != j</code> for which <code>dislikes[i] == dislikes[j]</code>.</li>
</ol>
<p>&nbsp;</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3614" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/886-ep217-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/886-ep217-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/886-ep217-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/886-ep217-1-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /><br />
<img loading="lazy" decoding="async" class="alignnone size-full wp-image-3613" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/886-ep217-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/886-ep217-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/886-ep217-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/886-ep217-2-768x432.png 768w" sizes="auto, (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"><br />
</ins></p>
<h1><strong>Solution: Graph Coloring</strong></h1>
<p>Color a node with one color, and color all it&#8217;s disliked nodes with another color, if can not finish return false.</p>
<p>Time complexity: O(V+E)</p>
<p>Space complexity: O(V+E)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++ / DFS</h2>
<div class="tabcontent">
</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 96 ms
class Solution {
public:
    bool possibleBipartition(int N, vector&lt;vector&lt;int&gt;&gt;&amp; dislikes) {
      g_ = vector&lt;vector&lt;int&gt;&gt;(N);
      for (const auto&amp; d : dislikes) {
        g_[d[0] - 1].push_back(d[1] - 1);
        g_[d[1] - 1].push_back(d[0] - 1);
      }
      colors_ = vector&lt;int&gt;(N, 0);  // 0: unknown, 1: red, -1: blue
      for (int i = 0; i &lt; N; ++i)
        if (colors_[i] == 0 &amp;&amp; !dfs(i, 1)) return false;
      return true;      
    }
private:
  vector&lt;vector&lt;int&gt;&gt; g_;
  vector&lt;int&gt; colors_;
  bool dfs(int cur, int color) {
    colors_[cur] = color;
    for (int nxt : g_[cur]) {
      if (colors_[nxt] == color) return false;      
      if (colors_[nxt] == 0 &amp;&amp; !dfs(nxt, -color)) return false;
    }
    return true;
  }
};</pre><p></div><h2 class="tabtitle">C++ / BFS</h2>
<div class="tabcontent">
</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 100 ms
class Solution {
public:
  bool possibleBipartition(int N, vector&lt;vector&lt;int&gt;&gt;&amp; dislikes) {
    vector&lt;vector&lt;int&gt;&gt; g(N);
    for (const auto&amp; d : dislikes) {
      g[d[0] - 1].push_back(d[1] - 1);
      g[d[1] - 1].push_back(d[0] - 1);
    }
    queue&lt;int&gt; q;
    vector&lt;int&gt; colors(N, 0);  // 0: unknown, 1: red, -1: blue
    for (int i = 0; i &lt; N; ++i) {
      if (colors[i] != 0) continue;
      q.push(i);
      colors[i] = 1;
      while (!q.empty()) {
        int cur = q.front(); q.pop();
        for (int nxt : g[cur]) {
          if (colors[nxt] == colors[cur]) return false;
          if (colors[nxt] != 0) continue;
          colors[nxt] = -colors[cur];
          q.push(nxt);
        }
      }
    }    
    return true;
  }
};</pre><p></div></div></p>
<h1><strong>Related Problem</strong></h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/graph/leetcode-785-is-graph-bipartite/">花花酱 LeetCode 785. Is Graph Bipartite?</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/graph/leetcode-886-possible-bipartition/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 813. Largest Sum of Averages</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-813-largest-sum-of-averages/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-813-largest-sum-of-averages/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 09 Apr 2018 16:13:04 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[average]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[partial sum]]></category>
		<category><![CDATA[partition]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2449</guid>

					<description><![CDATA[Problem 题目大意：把一个数组分成k个段，求每段平均值和的最大值。 https://leetcode.com/problems/largest-sum-of-averages/description/ We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group.&#8230;]]></description>
										<content:encoded><![CDATA[<p><iframe loading="lazy" title="花花酱 LeetCode 813. Largest Sum of Averages - 刷题找工作 EP179" width="500" height="375" src="https://www.youtube.com/embed/IPdShoUE9z8?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></p>
<h1><strong>Problem</strong></h1>
<p>题目大意：把一个数组分成k个段，求每段平均值和的最大值。</p>
<p><a href="https://leetcode.com/problems/largest-sum-of-averages/description/">https://leetcode.com/problems/largest-sum-of-averages/description/</a></p>
<p>We partition a row of numbers <code>A</code> into at most <code>K</code> adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?</p>
<p>Note that our partition must use every number in A, and that scores are not necessarily integers.</p>
<pre class="crayon:false"><strong>Example:</strong>
<strong>Input:</strong> 
A = [9,1,2,3,9]
K = 3
<strong>Output:</strong> 20
<strong>Explanation:</strong> 
The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned A into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
</pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>1 &lt;= A.length &lt;= 100</code>.</li>
<li><code>1 &lt;= A[i] &lt;= 10000</code>.</li>
<li><code>1 &lt;= K &lt;= A.length</code>.</li>
<li>Answers within <code>10^-6</code> of the correct answer will be accepted as correct.</li>
</ul>
<h1><strong>Idea</strong></h1>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2459" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/04/813-ep179.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/04/813-ep179.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/04/813-ep179-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/04/813-ep179-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></p>
<p>DP, use dp[k][i] to denote the largest average sum of partitioning first i elements into k groups.</p>
<h3><strong>Init</strong></h3>
<p>dp[1][i] = sum(a[0] ~ a[i &#8211; 1]) / i, for i in 1, 2, &#8230; , n.</p>
<h3><strong>Transition</strong></h3>
<p>dp[k][i] = max(dp[k &#8211; 1][j] + sum(a[j] ~ a[i &#8211; 1]) / (i &#8211; j)) for j in k &#8211; 1,&#8230;,i-1.</p>
<p>that is find the best j such that maximize dp[k][i]</p>
<p>largest sum of partitioning first j elements (a[0] ~ a[j &#8211; 1]) into k &#8211; 1 groups (already computed)</p>
<p>+ average of a[j] ~ a[i &#8211; 1] (partition a[j] ~ a[i &#8211; 1] into 1 group).</p>
<h3><strong>Answer</strong></h3>
<p>dp[K][n]</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: DP</strong></h1>
<p>Time complexity: O(kn^2)</p>
<p>Space complexity: O(kn)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 9 ms
class Solution {
public:
  double largestSumOfAverages(vector&lt;int&gt;&amp; A, int K) {
    const int n = A.size();
    vector&lt;vector&lt;double&gt;&gt; dp(K + 1, vector&lt;double&gt;(n + 1, 0.0));
    vector&lt;double&gt; sums(n + 1, 0.0);
    for (int i = 1; i &lt;= n; ++i) {
      sums[i] = sums[i - 1] + A[i - 1];
      dp[1][i] = static_cast&lt;double&gt;(sums[i]) / i;
    }
    for (int k = 2; k &lt;= K; ++k)
      for (int i = k; i &lt;= n; ++i)
        for (int j = k - 1; j &lt; i; ++j)
          dp[k][i] = max(dp[k][i], dp[k - 1][j] + (sums[i] - sums[j]) / (i - j));
    return dp[K][n];
  }
};</pre><p></div><h2 class="tabtitle">C++ O(n) space</h2>
<div class="tabcontent">
</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  double largestSumOfAverages(vector&lt;int&gt;&amp; A, int K) {
    const int n = A.size();
    vector&lt;double&gt; dp(n + 1, 0.0);
    vector&lt;double&gt; sums(n + 1, 0.0);
    for (int i = 1; i &lt;= n; ++i) {
      sums[i] = sums[i - 1] + A[i - 1];
      dp[i] = static_cast&lt;double&gt;(sums[i]) / i;
    }
    for (int k = 2; k &lt;= K; ++k) {
      vector&lt;double&gt; tmp(n + 1, 0.0);
      for (int i = k; i &lt;= n; ++i)
        for (int j = k - 1; j &lt; i; ++j)
          tmp[i] = max(tmp[i], dp[j] + (sums[i] - sums[j]) / (i - j));
      dp.swap(tmp);
    }
    return dp[n];
  }
};</pre><p></div></div></p>
<h1><strong>Solution 2: DFS + memoriation </strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 10 ms
class Solution {
public:
  double largestSumOfAverages(vector&lt;int&gt;&amp; A, int K) {
    const int n = A.size();
    m_ = vector&lt;vector&lt;double&gt;&gt;(K + 1, vector&lt;double&gt;(n + 1, 0.0));
    sums_ = vector&lt;double&gt;(n + 1, 0.0);
    for (int i = 1; i &lt;= n; ++i)
      sums_[i] = sums_[i - 1] + A[i - 1];
    return LSA(A, n, K);
  }
private:
  vector&lt;vector&lt;double&gt;&gt; m_;
  vector&lt;double&gt; sums_;
  
  // Largest sum of averages for first n elements in A paritioned into k groups
  double LSA(const vector&lt;int&gt;&amp; A, int n, int k) {
    if (m_[k][n] &gt; 0) return m_[k][n];
    if (k == 1) return sums_[n] / n;
    for (int i = k - 1; i &lt; n; ++i)
      m_[k][n] = max(m_[k][n], LSA(A, i, k - 1) + (sums_[n] - sums_[i]) / (n - i));
    return m_[k][n];
  }
};</pre><p></div></div></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-813-largest-sum-of-averages/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 763. Partition Labels</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-763-partition-labels/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-763-partition-labels/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 26 Jan 2018 06:08:15 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[Medium]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[partition]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1665</guid>

					<description><![CDATA[题目大意：把字符串分割成尽量多的不重叠子串，输出子串的长度数组。要求相同字符只能出现在一个子串中。 Problem: A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears&#8230;]]></description>
										<content:encoded><![CDATA[<p><iframe loading="lazy" title="花花酱 LeetCode 763. Partition Labels - 刷题找工作 EP161" width="500" height="375" src="https://www.youtube.com/embed/s-1W5FDJ0lw?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></p>
<p>题目大意：把字符串分割成尽量多的不重叠子串，输出子串的长度数组。要求相同字符只能出现在一个子串中。</p>
<p><strong>Problem:</strong></p>
<p>A string <code>S</code> of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.</p>
<p><b>Example 1:</b></p><pre class="urvanov-syntax-highlighter-plain-tag">Input: S = &quot;ababcbacadefegdehijhklij&quot;
Output: [9,7,8]
Explanation:
The partition is &quot;ababcbaca&quot;, &quot;defegde&quot;, &quot;hijhklij&quot;.
This is a partition so that each letter appears in at most one part.
A partition like &quot;ababcbacadefegde&quot;, &quot;hijhklij&quot; is incorrect, because it splits S into less parts.</pre><p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-1680" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/763-ep161.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/763-ep161.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/763-ep161-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/763-ep161-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></p>
<p><strong>Solution 0: Brute Force</strong></p>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 15 ms
class Solution {
public:
    vector&lt;int&gt; partitionLabels(string S) {
      vector&lt;int&gt; ans;
      size_t start = 0;
      size_t end = 0;
      for (size_t i = 0; i &lt; S.size(); ++i) {
        end = max(end, S.find_last_of(S[i]));
        if (i == end) {
          ans.push_back(end - start + 1);
          start = end + 1;
        }
      }
      return ans;
    }
};</pre><p>Python</p><pre class="urvanov-syntax-highlighter-plain-tag">"""
Author: Huahua
Running time : 48 ms
"""
class Solution:
  def partitionLabels(self, S):
    ans = []
    start, end = 0, 0
    for i in range(len(S)):
      end = max(end, S.rfind(S[i]))
      if i == end:
        ans.append(end - start + 1)
        start = end + 1
    return ans</pre><p>&nbsp;</p>
<p><strong>Solution 1: Greedy </strong></p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(26/128)</p>
<p>C++</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 6 ms
class Solution {
public:
    vector&lt;int&gt; partitionLabels(string S) {
      vector&lt;int&gt; last_index(128, 0);
      for (int i = 0; i &lt; S.size(); ++i)
        last_index[S[i]] = i;
      vector&lt;int&gt; ans;
      int start = 0;
      int end = 0;
      for (int i = 0; i &lt; S.size(); ++i) {
        end = max(end, last_index[S[i]]);
        if (i == end) {
          ans.push_back(end - start + 1);
          start = end + 1;
        }
      }
      return ans;
    }
};</pre><p>Java</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 16 ms
class Solution {
  public List&lt;Integer&gt; partitionLabels(String S) {
    int lastIndex[] = new int[128];
    for (int i = 0; i &lt; S.length(); ++i)
      lastIndex[(int)S.charAt(i)] = i;
    List&lt;Integer&gt; ans = new ArrayList&lt;&gt;();
    int start = 0;
    int end = 0;
    for (int i = 0; i &lt; S.length(); ++i) {
      end = Math.max(end, lastIndex[(int)S.charAt(i)]);
      if (i == end) {
        ans.add(end - start + 1);
        start = end + 1;
      }
    }
    return ans;
  }
}</pre><p>Python3</p><pre class="urvanov-syntax-highlighter-plain-tag">"""
Author: Huahua
Running time: 78 ms
"""
class Solution:
  def partitionLabels(self, S):
    last_index = {}
    for i, ch in enumerate(S):
      last_index[ch] = i
    start = end = 0
    ans = []
    for i, ch in enumerate(S):
      end = max(end, last_index[ch])
      if i == end:
        ans.append(end - start + 1)
        start = end + 1
    return ans</pre><p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-763-partition-labels/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 725. Split Linked List in Parts</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-725-split-linked-list-in-parts/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-725-split-linked-list-in-parts/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 14 Nov 2017 03:34:58 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[Medium]]></category>
		<category><![CDATA[head]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[partition]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=784</guid>

					<description><![CDATA[Problem: Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list &#8220;parts&#8221;. The length of each&#8230;]]></description>
										<content:encoded><![CDATA[<p><iframe loading="lazy" title="花花酱 LeetCode 725. Split Linked List in Parts - 刷题找工作 EP106" width="500" height="375" src="https://www.youtube.com/embed/fk8JTWhM-4U?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></p>
<p><strong>Problem:</strong></p>
<div class="question-description">
<p>Given a (singly) linked list with head node <code>root</code>, write a function to split the linked list into <code>k</code> consecutive linked list &#8220;parts&#8221;.</p>
<p>The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.</p>
<p>The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.</p>
<p>Return a List of ListNode&#8217;s representing the linked list parts that are formed.</p>
<p>Examples 1-&gt;2-&gt;3-&gt;4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]</p>
<p><b>Example 1:</b></p><pre class="urvanov-syntax-highlighter-plain-tag">Input: 
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The input and each element of the output are ListNodes, not arrays.
For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null.
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but it's string representation as a ListNode is [].</pre><p><b>Example 2:</b></p><pre class="urvanov-syntax-highlighter-plain-tag">Input: 
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.</pre><p><b>Note:</b></p>
<ul>
<li>The length of <code>root</code> will be in the range <code>[0, 1000]</code>.</li>
<li>Each value of a node in the input will be an integer in the range <code>[0, 999]</code>.</li>
<li><code>k</code> will be an integer in the range <code>[1, 50]</code>.</li>
</ul>
</div>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<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><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<div><strong>Idea:</strong></div>
<div></div>
<div>List + Simulation</div>
<div></div>
<div><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/725-ep106-1.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-792" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/725-ep106-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/725-ep106-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/725-ep106-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/725-ep106-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/11/725-ep106-1-624x351.png 624w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></div>
<div id="interviewed-div"></div>
<div><strong>Solution:</strong></div>
<div></div>
<div>C++</div>
<div>
<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Runtime: 9 ms
class Solution {
public:
    vector&lt;ListNode*&gt; splitListToParts(ListNode* root, int k) {
        int len = 0;
        for (ListNode* head = root; head; head = head-&gt;next) ++len;
        vector&lt;ListNode*&gt; ans(k, nullptr);
        int l = len / k;
        int r = len % k;        
        ListNode* head = root;
        ListNode* prev = nullptr;
        for (int i = 0; i &lt; k; ++i, --r) {
            ans[i] = head;
            for (int j = 0; j &lt; l + (r &gt; 0); ++j) {
                prev = head;
                head = head-&gt;next;
            }
            if (prev) prev-&gt;next = nullptr;
        }
        return ans;
    }
};</pre>
</div>
<p>Java</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Runtime: 4 ms
class Solution {
    public ListNode[] splitListToParts(ListNode root, int k) {
        ListNode[] ans = new ListNode[k];
        int len = 0;
        for (ListNode head = root; head != null; head = head.next) ++len;
        int l = len / k;
        int r = len % k;
        ListNode prev = null;   
        ListNode head = root;
        for (int i = 0; i &lt; k; ++i, --r) {
            ans[i] = head;
            int part_len = l + ((r &gt; 0) ? 1 : 0);
            for (int j = 0; j &lt; part_len; ++j) {
                prev = head;
                head = head.next;
            }            
            if (prev != null) prev.next = null;
        }
        return ans;
    }
}</pre><p>Python</p><pre class="urvanov-syntax-highlighter-plain-tag">"""
Author: Huahua
Runtime: 79 ms
"""
class Solution:
    def splitListToParts(self, root, k):
        total_len = 0
        head = root
        while head:
            total_len += 1
            head = head.next
        
        ans = [None for _ in range(k)]
        
        l, r = total_len // k, total_len % k
        
        prev, head = None, root
        
        for i in range(k):
            ans[i] = head
            for j in range(l + (1 if r &gt; 0 else 0)):
                prev, head = head, head.next
            if prev: prev.next = None
            r -= 1
        
        return ans</pre><p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-725-split-linked-list-in-parts/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
