I’m trying to solve the following Leetcode problem:
You are given a 2D integer array
intervalswhereintervals[i] => [starti, endi] represents all the integers fromstartitoendiinclusively.A containing set is an array
numswhere each interval from intervals has at least two integers in nums.For example, if
intervals = [[1,3], [3,7], [8,9]], then[1,2,4,7,8,9]and[2,3,4,8,9]are containing sets.Return the minimum possible size of a containing set.
I wrote the following code:
class Solution:
def intersectionSizeTwo(self, intervals):
intervals.sort()
result = []
for start, end in intervals:
count = 0
for x in result:
if start <= x <= end:
count += 1
while count < 2:
val = end - (1 - count)
result.append(val)
count += 1
return len(result)
Issue:
For some test cases, the function produces incorrect results.
Example:
intervals = [[1, 3], [3, 7], [5, 6]]
Expected output (based on known greedy approach):
4
Actual output from my code:
5
My questions:
What mistake exists in my logic for choosing points?
Why does picking points backward from the interval’s end sometimes fail with overlapping intervals?
What is the correct greedy strategy to solve this problem?
Any explanation or correction would be appreciated. I'm trying to understand why my approach breaks on certain overlapping cases.
result-- use asetinstead oflistfor that.resultat various points in the function.