Program to count number of intervals which are intersecting at given point in Python

Suppose we have a list of intervals and a value called point. Each interval interval[i] contains [si, ei] representing the start time and end time of interval i (both inclusive). We have to find the number of intervals that intersect at the given point.

So, if the input is like intervals = [[2, 6],[4, 10],[5, 9],[11, 14]] and point = 5, then the output will be 3, because at time 5, there are 3 intervals: [2, 6], [4, 10], and [5, 9].

Algorithm

To solve this, we will follow these steps −

  • Initialize count = 0

  • For each interval with start time i and end time j in intervals, do

    • If point >= i and point <= j, then

      • Increment count by 1

  • Return count

Example

Let us see the following implementation to get better understanding ?

def solve(intervals, point):
   count = 0
   for i, j in intervals:
      if point >= i and point <= j:
         count += 1
   return count

intervals = [[2, 6],[4, 10],[5, 9],[11, 14]]
point = 5
print(solve(intervals, point))
3

How It Works

The algorithm iterates through each interval and checks if the given point falls within the range [start, end] (inclusive). For point 5:

  • [2, 6]: 5 is between 2 and 6 ?

  • [4, 10]: 5 is between 4 and 10 ?

  • [5, 9]: 5 is between 5 and 9 ?

  • [11, 14]: 5 is not between 11 and 14 ?

Alternative Implementation

Using a more concise approach with list comprehension ?

def count_intersecting_intervals(intervals, point):
   return sum(1 for start, end in intervals if start <= point <= end)

intervals = [[2, 6],[4, 10],[5, 9],[11, 14]]
point = 5
result = count_intersecting_intervals(intervals, point)
print(f"Number of intervals intersecting at point {point}: {result}")
Number of intervals intersecting at point 5: 3

Conclusion

This problem is solved by iterating through all intervals and checking if the given point lies within each interval's range. The time complexity is O(n) where n is the number of intervals.

Updated on: 2026-03-26T15:14:24+05:30

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements