Leetcode 2960. Count Tested Devices After Test Operations
You are given an integer n
, which represents the number of devices in a lab from 1 to n
. You are also given a 2D integer array operations
where operations[i] = [left, right, testId]
means that all devices in the inclusive range [left, right]
are assigned to test with the test operation identifier testId
.
Find out how many devices were assigned at least one test operation from the list of operations provided.
Example:
Input: n = 5, operations = [[1, 2, 1], [2, 4, 2], [3, 5, 3]]
Output: 5
Explanation: The devices and their test assignments are:
Device 1 -> Test 1,
Device 2 -> Test 1, Test 2,
Device 3 -> Test 2, Test 3,
Device 4 -> Test 2, Test 3,
Device 5 -> Test 3
Out of the 5 devices, all devices are assigned at least one test operation.
operations
always valid and within the bounds of 1 to n
?
operations
array?
To solve this problem, we need to keep track of the devices assigned to any of the test operations. Here’s a potential plan:
assigned
of size n+1
(considering 1-based indexing) to track whether each device from 1 to n has been assigned any test. Initialize all values to false
.operations
array. For each operation [left, right, testId]
, mark all devices in the range [left, right]
as true
in the assigned
array.true
values in the assigned
array (ignoring the zeroth index).Here’s how you can implement this strategy in C++:
#include <vector>
int countTestedDevices(int n, std::vector<std::vector<int>>& operations) {
// Step 1: Initialize the 'assigned' array to false for each device.
std::vector<bool> assigned(n + 1, false);
// Step 2: Process each operation
for (const auto& op : operations) {
int left = op[0];
int right = op[1];
for (int i = left; i <= right; ++i) {
assigned[i] = true;
}
}
// Step 3: Count the number of devices that have been assigned at least one test.
int count = 0;
for (int i = 1; i <= n; ++i) {
if (assigned[i]) {
++count;
}
}
return count;
}
assigned
array takes O(n).n
devices. In the worst case, this step takes O(m*n), where m
is the number of operations.n
elements, which is O(n).Overall Time Complexity: O(m*n) in the worst case, because each operation might iterate through all n
devices.
Optimization Consideration:
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?