Filter Devices by Status, Threshold, and Registration Month
Arrays & HashingAuto-graded · 18 test casesLast updated
Tests nested JSON navigation, timestamp parsing in UTC, date-range filtering, and numeric comparison with multiple simultaneous predicates.
You are given a collection of device records and need to count how many satisfy a set of filtering criteria.
Write a function that accepts:
status_filter: a string representing the required device statusmin_threshold: a numeric value for comparisonmonth_year: a string in"MM-YYYY"format specifying a target month and yeardevices: a list of device dictionaries
Each device dictionary may contain:
"id": device identifier"timestamp": UTC milliseconds indicating when the device was registered"status": a status string"operatingParams": a nested dictionary that may contain"rootThreshold"(a number)- Other fields (irrelevant to this task)
Return the count of devices that meet all of the following conditions:
- The
"status"field exactly equalsstatus_filter(case-sensitive) - The
"rootThreshold"value inside"operatingParams"is strictly greater thanmin_threshold - The device was registered in the month and year specified by
month_year
If a device is missing any required field ("timestamp", "status", "operatingParams", or "rootThreshold"), exclude it from the count.
Constraints:
- 0 ≤ len(devices) ≤ 10⁵
month_yearis always a valid string in"MM-YYYY"format (leading zeros may or may not be present)timestampvalues, when present, are non-negative integers representing milliseconds since the Unix epochmin_thresholdandrootThresholdvalues are numeric (int or float)- All date comparisons must use UTC timezone
Examples
Example 1
Input: count_filtered_devices('active', 50, '01-2024', [{'id': 1, 'timestamp': 1704067200000, 'status': 'active', 'operatingParams': {'rootThreshold': 60}}, {'id': 2, 'timestamp': 1706745599000, 'status': 'active', 'operatingParams': {'rootThreshold': 50}}, {'id': 3, 'timestamp': 1706745600000, 'status': 'active', 'operatingParams': {'rootThreshold': 80}}, {'id': 4, 'timestamp': 1704067200000, 'status': 'inactive', 'operatingParams': {'rootThreshold': 90}}])
Output: 1
Example 2
Input: count_filtered_devices('inactive', 10, '12-2023', [{'id': 1, 'timestamp': 1703980800000, 'status': 'inactive', 'operatingParams': {'rootThreshold': 11}}, {'id': 2, 'timestamp': 1704067200000, 'status': 'inactive', 'operatingParams': {'rootThreshold': 20}}, {'id': 3, 'timestamp': 1703980800000, 'status': 'active', 'operatingParams': {'rootThreshold': 99}}])
Output: 1
Example 3
Input: count_filtered_devices('online', 0, '02-2024', [{'id': 1, 'timestamp': 1706745600000, 'status': 'online', 'operatingParams': {'rootThreshold': 1}}, {'id': 2, 'timestamp': 1709164800000, 'status': 'online', 'operatingParams': {'rootThreshold': 0}}, {'id': 3, 'timestamp': 1709251200000, 'status': 'online', 'operatingParams': {'rootThreshold': 2}}])
Output: 1
Hints
Hint 1
Convert milliseconds to seconds before creating a datetime object, and always use UTC timezone to avoid environment-dependent results.
Hint 2
Check the cheapest filters first: status comparison and threshold comparison happen before datetime conversion for better performance.
Hint 3
Use dictionary .get() to safely handle missing or optional fields without raising KeyError exceptions.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires filtering a list of device records based on three independent criteria: status match, threshold comparison, and temporal range. The solution applies each filter in sequence, rejecting devices that fail any criterion.
Algorithm:
- Parse the target month and year from
month_yearby splitting on"-"and converting to integers - Initialize a counter to zero
- For each device in the input list:
- Check if the status field matches
status_filterexactly; skip if not - Extract the timestamp and rootThreshold values, handling missing nested fields
- Verify that rootThreshold is strictly greater than
min_threshold; skip if not - Convert the timestamp from milliseconds to a UTC datetime object
- Compare the datetime's month and year against the target values; increment counter if both match
- Check if the status field matches
- Return the final count
Why This Works:
Each device either satisfies all predicates or fails at least one. By evaluating each condition independently and skipping devices that fail, we correctly identify the subset that meets all requirements. The order of checks matters for performance but not correctness: status and numeric comparisons are cheaper than datetime construction, so placing them first reduces unnecessary work.
Critical Details:
- UTC timezone: The
datetime.fromtimestamp()function defaults to local timezone, which produces system-dependent results. Passingtz=timezone.utcensures consistent behavior across all execution environments. - Milliseconds to seconds: Unix timestamps are typically in seconds, but the specification states values are in milliseconds. Dividing by 1000 before calling
fromtimestamp()is essential. - Strict inequality: The threshold comparison uses
>, not>=, per the requirement that rootThreshold must be strictly greater. - Safe field access: Using
.get()instead of bracket notation prevents crashes when fields are absent or the nested structure is incomplete.
Complexity
Time: O(n), where n is the number of devices. Each device requires a constant number of operations: dictionary lookups, one datetime conversion, and a few comparisons.
Space: O(1) auxiliary space beyond the input. Only a few variables (parsed month/year, counter, loop iteration variables) are maintained.
Solution
from datetime import datetime, timezone
from typing import List, Dict
def count_filtered_devices(status_filter, min_threshold, month_year, devices):
target_month, target_year = map(int, month_year.split("-"))
count = 0
for device in devices:
if device.get("status") != status_filter:
continue
timestamp_ms = device.get("timestamp")
operating_params = device.get("operatingParams") or {}
root_threshold = operating_params.get("rootThreshold")
if timestamp_ms is None or root_threshold is None or root_threshold <= min_threshold:
continue
device_date = datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc)
if device_date.month == target_month and device_date.year == target_year:
count += 1
return count