Points That Intersect With Cars - Problem
Imagine a long street where cars are parked at various segments. Each car occupies a continuous section of the street from its starting point to its ending point (inclusive).
You are given a 0-indexed 2D integer array nums where nums[i] = [starti, endi] represents the ith car parked from position starti to position endi on the number line.
Your task: Count how many integer points on the street are covered by at least one parked car.
Example: If cars are parked at [[3,6], [1,5], [4,7]], then points 1,2,3,4,5,6,7 are all covered, so the answer is 7.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [[3,6],[1,5],[4,7]]
โบ
Output:
7
๐ก Note:
Car 1 covers points [3,4,5,6], Car 2 covers [1,2,3,4,5], Car 3 covers [4,5,6,7]. Combined unique points: {1,2,3,4,5,6,7} = 7 points.
example_2.py โ No Overlap
$
Input:
nums = [[1,3],[5,8]]
โบ
Output:
7
๐ก Note:
Car 1 covers [1,2,3] and Car 2 covers [5,6,7,8]. No overlap, so total is 3 + 4 = 7 points.
example_3.py โ Single Car
$
Input:
nums = [[2,5]]
โบ
Output:
4
๐ก Note:
Only one car covering points [2,3,4,5], which gives us 4 points total.
Constraints
- 1 โค nums.length โค 100
- nums[i].length == 2
- 1 โค starti โค endi โค 100
- All coordinates are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Park the Cars
Each car occupies a continuous range of spots
2
Mark Occupied Spots
Add each occupied spot to our set
3
Count Unique Spots
The set size gives us the answer
Key Takeaway
๐ฏ Key Insight: Use a set data structure to automatically eliminate duplicate points when cars overlap, making the solution both simple and efficient.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code