<?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>interval Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/interval/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/interval/</link>
	<description></description>
	<lastBuildDate>Sun, 17 May 2020 04:12:10 +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>interval Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/interval/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1450. Number of Students Doing Homework at a Given Time</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1450-number-of-students-doing-homework-at-a-given-time/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1450-number-of-students-doing-homework-at-a-given-time/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 May 2020 04:11:55 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[brute force]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[interval]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6761</guid>

					<description><![CDATA[<p>Given two integer arrays&#160;startTime&#160;and&#160;endTime&#160;and given an integer&#160;queryTime. The&#160;ith&#160;student started doing their homework at the time&#160;startTime[i]&#160;and finished it at time&#160;endTime[i]. Return&#160;the number of students&#160;doing their homework&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1450-number-of-students-doing-homework-at-a-given-time/">花花酱 LeetCode 1450. Number of Students Doing Homework at a Given Time</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 two integer arrays&nbsp;<code>startTime</code>&nbsp;and&nbsp;<code>endTime</code>&nbsp;and given an integer&nbsp;<code>queryTime</code>.</p>



<p>The&nbsp;<code>ith</code>&nbsp;student started doing their homework at the time&nbsp;<code>startTime[i]</code>&nbsp;and finished it at time&nbsp;<code>endTime[i]</code>.</p>



<p>Return&nbsp;<em>the number of students</em>&nbsp;doing their homework at time&nbsp;<code>queryTime</code>. More formally, return the number of students where&nbsp;<code>queryTime</code>&nbsp;lays in the interval&nbsp;<code>[startTime[i], endTime[i]]</code>&nbsp;inclusive.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> startTime = [4], endTime = [4], queryTime = 4
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only student was doing their homework at the queryTime.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> startTime = [4], endTime = [4], queryTime = 5
<strong>Output:</strong> 0
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7
<strong>Output:</strong> 0
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5
<strong>Output:</strong> 5
</pre>



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



<ul><li><code>startTime.length == endTime.length</code></li><li><code>1 &lt;= startTime.length &lt;= 100</code></li><li><code>1 &lt;= startTime[i] &lt;= endTime[i] &lt;= 1000</code></li><li><code>1 &lt;=&nbsp;queryTime &lt;= 1000</code></li></ul>



<h2><strong>Solution: Brute Force</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="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int busyStudent(vector&lt;int&gt;&amp; startTime, vector&lt;int&gt;&amp; endTime, int queryTime) {
    int ans = 0;
    for (int i = 0; i &lt; startTime.size(); ++i)
      if (startTime[i] &lt;= queryTime &amp;&amp; queryTime &lt;= endTime[i]) ++ans;
    return ans;
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -&gt; int:
    return sum(s &lt;= queryTime &lt;= e for s, e in zip(startTime, endTime))</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1450-number-of-students-doing-homework-at-a-given-time/">花花酱 LeetCode 1450. Number of Students Doing Homework at a Given Time</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/array/leetcode-1450-number-of-students-doing-homework-at-a-given-time/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1348. Tweet Counts Per Frequency</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1348-tweet-counts-per-frequency/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1348-tweet-counts-per-frequency/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 01 Mar 2020 01:14:15 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[interval]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6381</guid>

					<description><![CDATA[<p>Implement the class&#160;TweetCounts&#160;that supports two methods: 1.&#160;recordTweet(string tweetName, int time) Stores the&#160;tweetName&#160;at the recorded&#160;time&#160;(in&#160;seconds). 2.&#160;getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) Returns the total&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1348-tweet-counts-per-frequency/">花花酱 LeetCode 1348. Tweet Counts Per Frequency</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>Implement the class&nbsp;<code>TweetCounts</code>&nbsp;that supports two methods:</p>



<p>1.<code>&nbsp;recordTweet(string tweetName, int time)</code></p>



<ul><li>Stores the&nbsp;<code>tweetName</code>&nbsp;at the recorded&nbsp;<code>time</code>&nbsp;(in&nbsp;<strong>seconds</strong>).</li></ul>



<p>2.<code>&nbsp;getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)</code></p>



<ul><li>Returns the total number of occurrences for the given&nbsp;<code>tweetName</code>&nbsp;per&nbsp;<strong>minute</strong>,&nbsp;<strong>hour</strong>, or&nbsp;<strong>day</strong>&nbsp;(depending on&nbsp;<code>freq</code>) starting from the&nbsp;<code>startTime</code>&nbsp;(in&nbsp;<strong>seconds</strong>) and ending at the&nbsp;<code>endTime</code>&nbsp;(in&nbsp;<strong>seconds</strong>).</li><li><code>freq</code>&nbsp;is always&nbsp;<strong>minute</strong><em>,&nbsp;</em><strong>hour</strong><em>&nbsp;or&nbsp;<strong>day</strong></em>, representing the time interval to get the total number of occurrences for the given&nbsp;<code>tweetName</code>.</li><li>The first time interval always starts from the&nbsp;<code>startTime</code>, so the time intervals are&nbsp;<code>[startTime, startTime + delta*1&gt;, &nbsp;[startTime + delta*1, startTime + delta*2&gt;, [startTime + delta*2, startTime + delta*3&gt;, ... , [startTime + delta*i,&nbsp;<strong>min</strong>(startTime + delta*(i+1), endTime + 1)&gt;</code>&nbsp;for some non-negative number&nbsp;<code>i</code>&nbsp;and&nbsp;<code>delta</code>&nbsp;(which depends on&nbsp;<code>freq</code>).&nbsp;&nbsp;</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]

<strong>Output</strong>
[null,null,null,null,[2]
[2,1],null,[4]]

<strong>Explanation</strong>
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10);                             // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60&gt; - &gt; 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60&gt; - &gt; 2 tweets, and 2) [60,61&gt; - &gt; 1 tweet.
tweetCounts.recordTweet("tweet3", 120);                            // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210);  // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211&gt; - &gt; 4 tweets.
</p>
</pre>



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



<ul><li>There will be at most <code>10000</code> operations considering both <code>recordTweet</code> and <code>getTweetCountsPerFrequency</code>.</li><li><code>0 &lt;= time, startTime, endTime &lt;= 10^9</code><br></li></ul>



<h2><strong>Solution: Hashtable + binary search</strong></h2>



<p>Time complexity: <br>Record: O(logn)<br>getCount: O(logn + |entries|)</p>



<p>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 TweetCounts {
public:
  TweetCounts() {
    m_.clear();
  }

  void recordTweet(string tweetName, int time) {
    m_[tweetName].insert(time);
  }

  vector&lt;int&gt; getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {
    auto tit = m_.find(tweetName);
    if (tit == m_.end()) return {};
    const set&lt;int&gt;&amp; s = tit-&gt;second;
    int delta = 1;
    if (freq == &quot;minute&quot;) delta = 60;
    else if (freq == &quot;hour&quot;) delta = 60 * 60;
    else if (freq == &quot;day&quot;) delta = 60 * 60 * 24;
    int slots = (endTime - startTime + delta - 1) / delta;
    vector&lt;int&gt; ans(slots);
    for (int i = startTime; i &lt;= endTime; i += delta) {
      auto it1 = s.lower_bound(i);
      auto it2 = s.lower_bound(min(i + delta, endTime + 1));
      ans.push_back(distance(it1, it2)); // O(|entries|)    
    }
    return ans;
  }
private:
  unordered_map&lt;string, set&lt;int&gt;&gt; m_;
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1348-tweet-counts-per-frequency/">花花酱 LeetCode 1348. Tweet Counts Per Frequency</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-1348-tweet-counts-per-frequency/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1272. Remove Interval</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-1272-remove-interval/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-1272-remove-interval/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 01 Dec 2019 04:50:58 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[intersection]]></category>
		<category><![CDATA[interval]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5893</guid>

					<description><![CDATA[<p>Given a&#160;sorted&#160;list of disjoint&#160;intervals, each interval&#160;intervals[i] = [a, b]&#160;represents the set of real numbers&#160;x&#160;such that&#160;a &#60;= x &#60; b. We remove the intersections between any&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-1272-remove-interval/">花花酱 LeetCode 1272. Remove Interval</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&nbsp;<strong>sorted</strong>&nbsp;list of disjoint&nbsp;<code>intervals</code>, each interval&nbsp;<code>intervals[i] = [a, b]</code>&nbsp;represents the set of real numbers&nbsp;<code>x</code>&nbsp;such that&nbsp;<code>a &lt;= x &lt; b</code>.</p>



<p>We remove the intersections between any interval in&nbsp;<code>intervals</code>&nbsp;and the interval&nbsp;<code>toBeRemoved</code>.</p>



<p>Return a&nbsp;<strong>sorted</strong>&nbsp;list of&nbsp;<code>intervals</code>&nbsp;after all such removals.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
<strong>Output:</strong> [[0,1],[6,7]]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> intervals = [[0,5]], toBeRemoved = [2,3]
<strong>Output:</strong> [[0,2],[3,5]]
</pre>



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



<ul><li><code>1 &lt;= intervals.length &lt;= 10^4</code></li><li><code>-10^9 &lt;= intervals[i][0] &lt; intervals[i][1] &lt;= 10^9</code></li></ul>



<h2><strong>Solution: Geometry</strong></h2>



<p>Time complexity: O(n)<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 Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; removeInterval(vector&lt;vector&lt;int&gt;&gt;&amp; intervals, vector&lt;int&gt;&amp; r) {
    vector&lt;vector&lt;int&gt;&gt; ans;
    for (const auto&amp; i : intervals)
      // Does not intersect
      if (i[1] &lt;= r[0] || i[0] &gt;= r[1])
        ans.push_back(i);
      else {
        // i starts first
        if (i[0] &lt; r[0]) 
          ans.push_back({i[0], r[0]});
        // i ends later
        if (i[1] &gt; r[1])
          ans.push_back({r[1], i[1]});        
      }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-1272-remove-interval/">花花酱 LeetCode 1272. Remove Interval</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/geometry/leetcode-1272-remove-interval/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 986. Interval List Intersections</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-986-interval-list-intersections/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-986-interval-list-intersections/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Feb 2019 06:48:57 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[interval]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4768</guid>

					<description><![CDATA[<p>Given two lists&#160;of&#160;closed&#160;intervals, each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. (Formally, a closed&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-986-interval-list-intersections/">花花酱 LeetCode 986. Interval List Intersections</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 two lists&nbsp;of&nbsp;<strong>closed</strong>&nbsp;intervals, each list of intervals is pairwise disjoint and in sorted order.</p>



<p>Return the intersection of these two interval lists.</p>



<p><em>(Formally, a closed interval&nbsp;<code>[a, b]</code>&nbsp;(with&nbsp;<code>a &lt;= b</code>) denotes&nbsp;the set of real numbers&nbsp;<code>x</code>&nbsp;with&nbsp;<code>a &lt;= x &lt;= b</code>.&nbsp; The&nbsp;intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval.&nbsp; For example, the intersection of [1, 3] and [2, 4] is [2, 3].)</em></p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/01/30/interval1.png" alt=""/></figure>



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
<strong>Output: </strong>[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
<strong>Reminder: </strong>The inputs and the desired output are lists of Interval&nbsp;objects, and not arrays or lists.
</pre>



<p><strong>Note:</strong></p>



<ol><li><code>0 &lt;= A.length &lt; 1000</code></li><li><code>0 &lt;= B.length &lt; 1000</code></li><li><code>0 &lt;= A[i].start, A[i].end, B[i].start, B[i].end &lt; 10^9</code></li></ol>



<h2><strong>Solution: Two&nbsp;pointers</strong></h2>



<p>Time complexity: O(m + n)<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, running time: 36 ms, 925.7 KB
class Solution {
public:
  vector&lt;Interval&gt; intervalIntersection(vector&lt;Interval&gt;&amp; A, vector&lt;Interval&gt;&amp; B) {
    size_t i = 0;
    size_t j = 0;
    vector&lt;Interval&gt; ans;
    while (i &lt; A.size() &amp;&amp; j &lt; B.size()) {
      const int s = max(A[i].start, B[j].start);
      const int e = min(A[i].end, B[j].end);
      if (s &lt;= e) ans.emplace_back(s, e);
      if (A[i].end &lt; B[j].end)
        ++i;
      else
        ++j;
    }
    return ans;
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua, running time: 96 ms, 7.6 MB
class Solution:
  def intervalIntersection(self, A: 'List[Interval]', B: 'List[Interval]') -&gt; 'List[Interval]':
    i, j, ans = 0, 0, []
    while i &lt; len(A) and j &lt; len(B):
      s = max(A[i].start, B[j].start)
      e = min(A[i].end, B[j].end)
      if s &lt;= e:
        ans.append(Interval(s, e))
      if A[i].end &lt; B[j].end:
        i += 1
      else:
        j += 1
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-986-interval-list-intersections/">花花酱 LeetCode 986. Interval List Intersections</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/geometry/leetcode-986-interval-list-intersections/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 759. Employee Free Time</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-759-employee-free-time/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-759-employee-free-time/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 09 Jan 2018 02:11:26 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[Hard]]></category>
		<category><![CDATA[intersection]]></category>
		<category><![CDATA[interval]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[sweep line]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1574</guid>

					<description><![CDATA[<p>题目大意：给你每个员工的日历，让你找出所有员工都有空的时间段。 Problem: We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-759-employee-free-time/">花花酱 LeetCode 759. Employee Free Time</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/VTgF52uGK0Y?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你每个员工的日历，让你找出所有员工都有空的时间段。</p>
<p><strong>Problem:</strong></p>
<p>We are given a list <code>schedule</code> of employees, which represents the working time for each employee.</p>
<p>Each employee has a list of non-overlapping <code>Intervals</code>, and these intervals are in sorted order.</p>
<p>Return the list of finite intervals representing <b>common, positive-length free time</b> for <i>all</i> employees, also in sorted order.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
Output: [[3,4]]
Explanation:
There are a total of three employees, and all common
free time intervals would be [-inf, 1], [3, 4], [10, inf].
We discard any intervals that contain inf as they aren't finite.</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
Output: [[5,6],[7,9]]</pre><p>(Even though we are representing <code>Intervals</code> in the form <code>[x, y]</code>, the objects inside are <code>Intervals</code>, not lists or arrays. For example, <code>schedule[0][0].start = 1, schedule[0][0].end = 2</code>, and <code>schedule[0][0][0]</code> is not defined.)</p>
<p>Also, we wouldn&#8217;t include intervals like [5, 5] in our answer, as they have zero length.</p>
<p><b>Note:</b></p>
<ol>
<li><code>schedule</code> and <code>schedule[i]</code> are lists with lengths in range <code>[1, 50]</code>.</li>
<li><code>0 &lt;= schedule[i].start &lt; schedule[i].end &lt;= 10^8</code>.</li>
</ol>
<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>
<p><strong>Idea:</strong></p>
<p>Merge Intervals (virtually)</p>
<p><img class="alignnone wp-image-1580 size-full" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/759-ep154.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/759-ep154.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/759-ep154-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/759-ep154-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><strong>Solution:</strong></p>
<p>C++</p>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(n)</p>
<p>n is the total number of intervals, n &lt;= 2500</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 81 ms
class Solution {
public:
    vector&lt;Interval&gt; employeeFreeTime(vector&lt;vector&lt;Interval&gt;&gt;&amp; schedule) {
      vector&lt;Interval&gt; all;
      for (const auto intervals : schedule)
        all.insert(all.end(), intervals.begin(), intervals.end());
      std::sort(all.begin(), all.end(), 
                [](const Interval&amp; a, const Interval&amp; b){
                  return a.start &lt; b.start;
                });
      vector&lt;Interval&gt; ans;
      int end = all.front().end;
      for (const Interval&amp; busy : all) {
        if (busy.start &gt; end) 
          ans.emplace_back(end, busy.start);  
        end = max(end, busy.end);
      }
      return ans;
    }
};</pre><p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">[解题报告] LeetCode 56. Merge Intervals</a></li>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/">[解题报告] LeetCode 57. Insert Interval</a></li>
<li><a href="http://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-729-my-calendar-i/">[解题报告] LeetCode 729. My Calendar &#8211; 花花酱</a></li>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-731-my-calendar-ii/">[解题报告] LeetCode 731. My Calendar II &#8211; 花花酱</a></li>
<li><a href="http://zxi.mytechroad.com/blog/geometry/732-my-calendar-iii/">花花酱 LeetCode 732. My Calendar III</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-759-employee-free-time/">花花酱 LeetCode 759. Employee Free Time</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/geometry/leetcode-759-employee-free-time/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 57. Insert Interval</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Oct 2017 04:58:15 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[interval]]></category>
		<category><![CDATA[merge]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=586</guid>

					<description><![CDATA[<p>Problem: Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/">花花酱 LeetCode 57. Insert Interval</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/oWHWDI2eOHY?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<div class="question-description">
<p>Given a set of <i>non-overlapping</i> intervals, insert a new interval into the intervals (merge if necessary).</p>
<p>You may assume that the intervals were initially sorted according to their start times.</p>
<p><b>Example 1:</b><br />
Given intervals <code>[1,3],[6,9]</code>, insert and merge <code>[2,5]</code> in as <code>[1,5],[6,9]</code>.</p>
<p><b>Example 2:</b><br />
Given <code>[1,2],[3,5],[6,7],[8,10],[12,16]</code>, insert and merge <code>[4,9]</code> in as <code>[1,2],[3,10],[12,16]</code>.</p>
<p>This is because the new interval <code>[4,9]</code> overlaps with <code>[3,5],[6,7],[8,10].</code></p>
<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>
<p><strong>Idea:</strong></p>
<p>Find the position of the new interval, insert it into the list and call MergeIntervals in <a href="http://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">LeetCode 56</a></p>
</div>
<p><strong>Solution:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 16 ms
class Solution {
public:
    vector&lt;Interval&gt; insert(vector&lt;Interval&gt;&amp; intervals, Interval newInterval) {
        auto it = intervals.begin();
        while (it != intervals.end() &amp;&amp; newInterval.start &gt; it-&gt;start) ++it;
        intervals.insert(it, newInterval);
        
        // Merge intervals without sorting
        vector&lt;Interval&gt; ans;        
        for (const auto&amp; interval : intervals) {
            if (ans.empty() || interval.start &gt; ans.back().end) {
                ans.push_back(interval);
            } else {
                ans.back().end = max(ans.back().end, interval.end);
            }
        }
        
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 78 ms
"""
class Solution(object):
    def insert(self, intervals, newInterval):
        
        index = len(intervals)
        for i in range(len(intervals)):
            if newInterval.start &lt; intervals[i].start:
                index = i
                break
        
        intervals.insert(index, newInterval)
        
        ans = []
        for interval in intervals:
            if not ans or interval.start &gt; ans[-1].end:
                ans.append(interval)
            else:
                ans[-1].end = max(ans[-1].end, interval.end)
        return ans</pre><p>&nbsp;</p>
<p>Solution 2:</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 13 ms
class Solution {
public:
    vector&lt;Interval&gt; insert(vector&lt;Interval&gt;&amp; intervals, Interval newInterval) {
        vector&lt;Interval&gt; l;
        vector&lt;Interval&gt; r;
        int start = newInterval.start;
        int end = newInterval.end;
        for (const Interval&amp; interval : intervals) {
            if (interval.end &lt; start)
                l.push_back(interval);
            else if (interval.start &gt; end)
                r.push_back(interval);
            else {
                start = min(start, interval.start);
                end = max(end, interval.end);
            }                
        }
        
        vector&lt;Interval&gt; ans(std::move(l));
        ans.emplace_back(start, end);
        ans.insert(ans.end(), r.begin(), r.end());
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 68 ms
"""
class Solution(object):
    def insert(self, intervals, newInterval):
        start, end = newInterval.start, newInterval.end
        l, r = [], []        
        for interval in intervals:
            if interval.end &lt; start: l += interval, 
            elif interval.start &gt; end: r += interval,
            else: 
                start = min(start, interval.start)
                end = max(end, interval.end)
        return l + [Interval(start, end)] + r</pre><p>&nbsp;</p>
<p><strong>Related problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">[解题报告] LeetCode 56. Merge Intervals</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-218-the-skyline-problem/">[解题报告] LeetCode 218. The Skyline Problem</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/">花花酱 LeetCode 57. Insert Interval</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/geometry/leetcode-57-insert-interval/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 56. Merge Intervals</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Oct 2017 03:13:20 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[interval]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sweep line]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=578</guid>

					<description><![CDATA[<p>Problem: Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18]. Idea: Sweep line Solution: C++ [crayon-66389d127fc5f089754374/] Python [crayon-66389d127fc61924077778/] &#160; Related Problems:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">花花酱 LeetCode 56. Merge Intervals</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/6tLHjei-f0I?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given a collection of intervals, merge all overlapping intervals.</p>
<p>For example,<br />
Given <code>[1,3],[2,6],[8,10],[15,18]</code>,<br />
return <code>[1,6],[8,10],[15,18]</code>.</p>
<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>
<p><strong>Idea:</strong></p>
<p>Sweep line</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1.png"><img class="alignnone size-full wp-image-584" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/56-ep85-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Solution: </strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 12 ms
class Solution {
public:
    vector&lt;Interval&gt; merge(vector&lt;Interval&gt;&amp; intervals) {
        if (intervals.empty()) return {};
        
        std::sort(intervals.begin(), intervals.end(), 
                  [](const Interval&amp; a, const Interval&amp; b){
                        return a.start &lt; b.start;
                    });
        
        vector&lt;Interval&gt; ans;        
        for (const auto&amp; interval : intervals) {
            if (ans.empty() || interval.start &gt; ans.back().end) {
                ans.push_back(interval);
            } else {
                ans.back().end = max(ans.back().end, interval.end);
            }
        }
        
        return ans;
    }
};</pre><p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 69 ms
"""
class Solution(object):
    def merge(self, intervals):
        ans = []
        for interval in sorted(intervals, key=lambda x: x.start):
            if not ans or interval.start &gt; ans[-1].end:
                ans.append(interval)
            else:
                ans[-1].end = max(ans[-1].end, interval.end)
        return ans</pre><p>&nbsp;</p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/geometry/leetcode-57-insert-interval/">[解题报告] LeetCode 57. Insert Interval</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-218-the-skyline-problem/">[解题报告] LeetCode 218. The Skyline Problem</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-56-merge-intervals/">花花酱 LeetCode 56. Merge Intervals</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/geometry/leetcode-56-merge-intervals/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
