Skip to content
>GLB_
Go back

Counting Covered Points on a Number Line

Introduction

Algorithmic challenges often involve intervals and can initially seem complex. One such problem is determining how many unique points are covered by a set of intervals on a number line. In this post, we’ll examine a solution to this problem and explore potential improvements.

Problem Statement

Given a number line with several intervals representing parked cars, where each interval [start, end] covers all integer points from start to end, the goal is to find out how many distinct integer points are covered by at least one car.

Example 1:

Example 2:

Solution Approach

Here is a straightforward solution to the problem:

def numberOfPoints(self, nums: List[List[int]]) -> int:
    number_set = set()
    for elem in nums:
        for i in range(elem[0], elem[1] + 1):
            number_set.add(i)
    return len(number_set)

Explanation

  1. Use of a Set: The solution utilizes a set, number_set, to store each unique point covered by the intervals. This is effective because sets automatically handle duplicate values, ensuring that each point is counted only once.
  2. Iterating through Intervals: For each interval [start, end], the solution adds every integer point from start to end into the set.
  3. Counting Unique Points: After processing all intervals, the length of the set gives the number of unique points covered.

Potential Improvements

While the solution is straightforward, there are ways to potentially improve it:


Share this post:

Previous Post
How to Implement MVC in CodeIgniter to Clean Up Your Views
Next Post
Renaming Modules in Python for Clarity and Accuracy