1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Why does my Python solution for selecting 2 points from each interval give incorrect...

Discussão em 'Python' iniciado por Stack, Novembro 22, 2025.

  1. Stack

    Stack Membro Participativo

    I’m trying to solve the following Leetcode problem:


    You are given a 2D integer array intervals where intervals = > [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.

    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:


    1. What mistake exists in my logic for choosing points?


    2. Why does picking points backward from the interval’s end sometimes fail with overlapping intervals?


    3. 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.

    Continue reading...

Compartilhe esta Página