HardNo. 0757

Set Intersection Size At Least Two — LeetCode 757 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Sorting
Reading time
3 min

The problem

You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively. A containing set is an array nums where each interval from intervals has at least two integers in nums.

Example

Input
intervals = [[1,3],[3,7],[8,9]]
Output
5
Explanation
let nums = [2, 3, 4, 8, 9].

Python solution

PythonSolution
class Solution:
    def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:
        intervals.sort(key=lambda x: (x[1], -x[0]))
        s = e = -1
        ans = 0
        for a, b in intervals:
            if a <= s:
                continue
            if a > e:
                ans += 2
                s, e = b - 1, b
            else:
                ans += 1
                s, e = e, b
        return ans

Complexity

Time
O(n × log n)
Space · auxiliary
O(log n)where n is the number of intervals

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 757. Set Intersection Size At Least Two is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0179Largest NumberMedium
0324Wiggle Sort IIMedium
0452Minimum Number of Arrows to Burst BalloonsMedium
0455Assign CookiesEasy
0502IPOHard
0561Array PartitionEasy

Frequently asked questions

How hard is LeetCode 757. Set Intersection Size At Least Two?

LeetCode 757. Set Intersection Size At Least Two is rated Hard on LeetCode.

What is the time complexity of LeetCode 757. Set Intersection Size At Least Two?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 757. Set Intersection Size At Least Two?

The Python solution on this page uses O(log n), where n is the number of intervals auxiliary space.

What topics does LeetCode 757. Set Intersection Size At Least Two cover?

LeetCode 757. Set Intersection Size At Least Two is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.