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
Street Parking CoverageParking Street๐Ÿš— Car ASpots 3-6๐Ÿš™ Car BSpots 1-5๐Ÿš Car CSpots 4-7Occupied Spots Set:{1, 2, 3, 4, 5, 6, 7}Total: 7 spots coveredThe set automatically handles overlapping cars!
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.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
23.4K Views
Medium Frequency
~8 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen