KatInterview

Count Active Surveillance Cameras at Each Minute

Greedy & IntervalsAuto-graded · 17 test cases
MediumAuto-gradedGreedy & Intervalssweep lineintervalsgreedy

Last updated

Tests the sweep-line technique by computing, for each minute in a query list, how many camera recording intervals are active at that exact moment.

Count Active Surveillance Cameras at Each Minute

A building's security system logs camera activity as a list of recording intervals. Each interval is represented as [start, end] (both inclusive), meaning that camera was actively recording from minute start through minute end.

Given a list of such recording intervals and a list of query minutes, return a list where the i-th element is the number of cameras that are actively recording at minute queries[i].

A camera is active at minute t if start <= t <= end.

Input

  • intervals: a list of [start, end] pairs, where each start and end is an integer.
  • queries: a list of integers, each representing a minute to query.

Output

Return a list of integers of the same length as queries, where the i-th element is the count of intervals [start, end] such that start <= queries[i] <= end.

The output list must be in the same order as the input queries list.

Constraints

  • 0 <= len(intervals) <= 2000
  • 0 <= len(queries) <= 2000
  • For each interval [start, end]: 0 <= start <= end <= 10^6
  • 0 <= queries[i] <= 10^6
  • Intervals may overlap and duplicate intervals are allowed.
  • queries may contain duplicate values; each is answered independently.

Examples

Example 1

Input: count_active_cameras([[1, 5], [2, 8], [6, 10]], [3, 6, 9])

Output: [2, 2, 1]

Example 2

Input: count_active_cameras([[0, 0], [0, 1], [1, 1]], [0, 1])

Output: [2, 2]

Example 3

Input: count_active_cameras([], [4, 7])

Output: [0, 0]

Hints

Hint 1

Sort the queries (while remembering their original positions) and process them in order — this lets you advance through interval events without re-scanning from scratch.

Hint 2

Build two sorted event lists: one for interval starts and one for interval ends. As you sweep through sorted query values, add cameras whose start <= current query and remove cameras whose end < current query.

Hint 3

Use two pointers — one into the sorted starts array and one into the sorted ends array — advancing each pointer as needed while you process each query in sorted order. Restore original query order at the end.