#757
Set Intersection Size At Least Two
HardArrayGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach leverages a greedy strategy. By sorting the intervals and ensuring that we always add the largest possible integers to our set, we can minimize the size of the containing set while still satisfying the requirement of covering each interval with at least two integers.
⚙️
Algorithm
4 steps- 1Step 1: Sort the intervals by their end points.
- 2Step 2: Initialize an empty set to hold the integers and a variable to track the last added integer.
- 3Step 3: Iterate through the sorted intervals and for each interval, check if the last added integer can cover it; if not, add two integers from the end of the current interval.
- 4Step 4: Continue until all intervals are covered.
solution.py15 lines
1# Full working Python code
2
3def minSetSize(intervals):
4 intervals.sort(key=lambda x: x[1])
5 nums = []
6 last_added = -1
7 for start, end in intervals:
8 if last_added < start:
9 nums.append(end - 1)
10 nums.append(end)
11 last_added = end
12 elif last_added == start:
13 nums.append(end)
14 last_added = end
15 return len(nums)ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) because we store the integers in a list.
- 1Greedy algorithms often provide efficient solutions for covering problems.
- 2Sorting the intervals helps in systematically choosing the best integers to cover multiple intervals.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.