Points That Intersect With Cars - Problem

You are given a 0-indexed 2D integer array nums representing the coordinates of cars parking on a number line. For any index i, nums[i] = [starti, endi] where starti is the starting point of the ith car and endi is the ending point of the ith car.

Return the number of integer points on the line that are covered with any part of a car.

Input & Output

Example 1 — Basic Overlapping Cars
$ Input: nums = [[3,6],[1,5],[4,7]]
Output: 7
💡 Note: Cars cover points: [3,6] covers 3,4,5,6; [1,5] covers 1,2,3,4,5; [4,7] covers 4,5,6,7. Combined unique points: 1,2,3,4,5,6,7 = 7 total points.
Example 2 — Non-overlapping Cars
$ Input: nums = [[1,3],[5,8]]
Output: 7
💡 Note: Car [1,3] covers points 1,2,3 (3 points). Car [5,8] covers points 5,6,7,8 (4 points). No overlap, so total is 3 + 4 = 7 points.
Example 3 — Single Car
$ Input: nums = [[2,5]]
Output: 4
💡 Note: Only one car covering points 2,3,4,5, which gives us 4 integer points total.

Constraints

  • 1 ≤ nums.length ≤ 100
  • nums[i].length == 2
  • 1 ≤ starti ≤ endi ≤ 100

Visualization

Tap to expand
Points That Intersect With Cars INPUT 1 2 3 4 5 6 7 Car 1: [3,6] Car 2: [1,5] Car 3: [4,7] Input Array: nums = [[3,6], [1,5], [4,7]] 3 cars on number line covering points 1 to 7 ALGORITHM STEPS 1 Initialize Hash Set Create empty set for points 2 Iterate Each Car Loop through nums array 3 Add Points to Set For i in [start, end]: add i 4 Return Set Size Count unique points Hash Set Contents: 1 2 3 4 5 6 7 FINAL RESULT Covered Points: 1 2 3 4 5 6 7 Output: 7 7 unique integer points are covered by at least one car OK Key Insight: Using a Hash Set automatically handles overlapping intervals by storing only unique points. Time Complexity: O(n * m) where n = number of cars, m = max interval length. Space: O(total unique points). TutorialsPoint - Points That Intersect With Cars | Hash Set Approach
Asked in
Google 12 Amazon 8 Microsoft 6
12.5K Views
Medium Frequency
~15 min Avg. Time
384 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