Count Monthly Devices Above Threshold
Medium · Data Manipulation (SQL/Python) · Software Engineer · Online Assessment
Problem Statement
You are given a list of sensor telemetry records devices (collected from pages of a device-inventory service), a target state string status_query, a numeric cutoff threshold, and a month-year string date_str formatted as "MM-YYYY".
Each dictionary in devices represents one registered hardware unit with the following fields:
"id"(int): unique identifier of the unit."timestamp"(int): registration instant recorded in UTC epoch milliseconds (milliseconds since1970-01-01T00:00:00Z)."status"(str): operational state label (such as"RUNNING","STOPPED","MALFUNCTIONING", or"IDLE")."operatingParams"(dict): nested dictionary of diagnostic readings that always includes"rootThreshold"(intorfloat) and may also include"rotorSpeed"and"slack".- Optional metadata dictionaries such as
"asset"({"id": ..., "alias": ...}) and"parent"({"id": ..., "alias": ...}).
Implement num_devices(status_query, threshold, date_str, devices) to return the count of records in devices that satisfy all three conditions below:
- Exact state match:
device["status"] == status_query(case-sensitive). - UTC registration month:
device["timestamp"], interpreted in UTC, falls inside the calendar month and year specified bydate_str("MM-YYYY"). - Strict threshold check:
device["operatingParams"]["rootThreshold"] > threshold(records equal tothresholddo not qualify).
(Note: When backed by a live paginated HTTP endpoint returning JSON pages with page, per_page, total, total_pages, and data, devices corresponds to the combined data lists across pages and may still contain mixed status values.)
Examples
Example 1
status_query = "RUNNING"
threshold = 75.0
date_str = "05-2024"
devices = [
{"id": 101, "timestamp": 1714521600000, "status": "RUNNING", "operatingParams": {"rootThreshold": 82.5}},
{"id": 102, "timestamp": 1715731200000, "status": "RUNNING", "operatingParams": {"rootThreshold": 75.0}},
{"id": 103, "timestamp": 1717199999000, "status": "RUNNING", "operatingParams": {"rootThreshold": 91.0}},
{"id": 104, "timestamp": 1717200000000, "status": "RUNNING", "operatingParams": {"rootThreshold": 95.0}},
{"id": 105, "timestamp": 1715342400000, "status": "STOPPED", "operatingParams": {"rootThreshold": 88.0}},
]
Output: 2
Explanation: May 2024 in UTC spans [1714521600000, 1717200000000). Unit 101 (2024-05-01 00:00:00 UTC, 82.5 > 75.0) and unit 103 (2024-05-31 23:59:59 UTC, 91.0 > 75.0) satisfy every check. Unit 102 ties threshold (75.0), unit 104 lands on 2024-06-01 00:00:00 UTC, and unit 105 has status "STOPPED".
Example 2
status_query = "MALFUNCTIONING"
threshold = 25.5
date_str = "12-2024"
devices = [
{"id": 201, "timestamp": 1734220800000, "status": "MALFUNCTIONING", "operatingParams": {"rootThreshold": 25.6}},
{"id": 202, "timestamp": 1735689600000, "status": "MALFUNCTIONING", "operatingParams": {"rootThreshold": 40.0}},
{"id": 203, "timestamp": 1702598400000, "status": "MALFUNCTIONING", "operatingParams": {"rootThreshold": 50.0}},
]
Output: 1
Explanation: Only unit 201 (2024-12-15 00:00:00 UTC, 25.6 > 25.5) was registered during December 2024. Unit 202 falls on 2025-01-01 00:00:00 UTC, and unit 203 was registered in December 2023.
Example 3
status_query = "IDLE"
threshold = 10.0
date_str = "08-2023"
devices = [
{"id": 301, "timestamp": 1691625600000, "status": "IDLE", "operatingParams": {"rootThreshold": 10.0}},
{"id": 302, "timestamp": 1691625600000, "status": "RUNNING", "operatingParams": {"rootThreshold": 45.0}},
]
Output: 0
Explanation: Unit 301 was registered in August 2023 with status "IDLE", but rootThreshold is 10.0 (not strictly above 10.0). Unit 302 does not match "IDLE".
Constraints
0 <= len(devices) <= 10^5date_stralways follows"MM-YYYY"with"01" <= MM <= "12"and1970 <= YYYY <= 2100.device["timestamp"]is a non-negative integer in UTC epoch milliseconds.thresholdanddevice["operatingParams"]["rootThreshold"]areintorfloatvalues in[-10^9, 10^9].status_queryanddevice["status"]are non-empty strings.
Step-by-step walkthrough
Understand the inputs and the three filter rules
Each item in
devicesis a dictionary representing one hardware sensor record, shaped like:{ "id": 101, "timestamp": 1714521600000, # UTC milliseconds since Jan 1, 1970 "status": "RUNNING", "operatingParams": { "rotorSpeed": 3000, "slack": 0.5, "rootThreshold": 82.5, }, }We need to return how many records satisfy all three conditions at once:
- Status matches:
device["status"] == status_query. Even when records originate from a filtered endpoint, thedeviceslist passed tonum_devicescan contain mixed statuses (Example 1 includes a"STOPPED"record), so we must verify the status explicitly. - Registered in the target UTC month:
device["timestamp"](in UTC milliseconds) falls inside the calendar month and year given bydate_strin"MM-YYYY"format (such as"05-2024"for May 2024). - Strictly above threshold:
device["operatingParams"]["rootThreshold"] > threshold. Equality does not count.
- Status matches:
Key idea: turn the month into a half-open UTC window
A tempting first approach is to convert every device's
timestampinto adatetimeobject and checkdt.month == month and dt.year == year. That works if done carefully, but it builds a newdatetimeobject on every iteration and invites a classic bug: callingdatetime.fromtimestamp(...)withouttz=timezone.utcuses the machine's local time zone, shifting devices near midnight into the wrong month.Instead, we can convert
date_stronce into two integers[start_ms, end_ms):start_ms:00:00:00.000 UTCon day 1 of the target month (included).end_ms:00:00:00.000 UTCon day 1 of the next month (excluded).
UTC timeline (milliseconds): ... ---+-----------------------------------------------+--- ... start_ms end_ms 2024-05-01 2024-06-01 00:00:00.000 UTC 00:00:00.000 UTC [================== included ===================) ^ excluded!Using a half-open range
start_ms <= timestamp_ms < end_msgives us two big wins for free: - We never have to look up whether the month has 28, 29, 30, or 31 days (leap-year Februaries end cleanly at March 1). - We never miss devices added at23:59:59.500on the last day of the month, which happens when people hardcode23:59:59as an end time.Write the month-window helper
To compute
(start_ms, end_ms)from"MM-YYYY":- Split
date_stron"-"and convert both pieces withint(...)(int("05")becomes5). - Find the next month: if
month == 12, the next month is January (1) ofyear + 1; otherwise it ismonth + 1of the sameyear. - Construct both
datetimeobjects withtzinfo=timezone.utc. Leaving outtzinfowould make.timestamp()interpret the date in local system time! - Multiply
int(dt.timestamp())by1000because.timestamp()is in seconds, while device timestamps are in milliseconds.
from datetime import datetime, timezone def _month_window_ms(date_str: str) -> Tuple[int, int]: """Return the half-open UTC window [start_ms, end_ms) for 'MM-YYYY' in epoch milliseconds.""" month_text, year_text = date_str.split("-") month = int(month_text) year = int(year_text) # Roll December forward to January of the next year so we never hardcode month lengths (28/29/30/31). if month == 12: next_year = year + 1 next_month = 1 else: next_year = year next_month = month + 1 # Pin both calendar instants to UTC; a naive datetime would use the machine's local time zone. start_utc = datetime(year, month, 1, tzinfo=timezone.utc) end_utc = datetime(next_year, next_month, 1, tzinfo=timezone.utc) # .timestamp() returns seconds since 1970-01-01 UTC; multiply by 1000 to match device millisecond timestamps. start_ms = int(start_utc.timestamp()) * 1000 end_ms = int(end_utc.timestamp()) * 1000 return start_ms, end_ms- Split
Write the device-filtering loop
With
(start_ms, end_ms)precomputed, filteringdevicesis a clean single pass using three guard checks:- Skip if
device["status"] != status_query. - Skip if
timestamp_ms < start_ms(too early) ortimestamp_ms >= end_ms(already in the next month or later). - Increment
matching_countonly ifdevice["operatingParams"]["rootThreshold"] > threshold(strict>).
def num_devices(status_query: str, threshold: float, date_str: str, devices: List[Dict]) -> int: start_ms, end_ms = _month_window_ms(date_str) matching_count = 0 for device in devices: if device["status"] != status_query: continue timestamp_ms = device["timestamp"] if timestamp_ms < start_ms or timestamp_ms >= end_ms: continue root_threshold = device["operatingParams"]["rootThreshold"] if root_threshold > threshold: matching_count += 1 return matching_count- Skip if
Trace Example 1 step by step
Call:
num_devices("RUNNING", 75.0, "05-2024", devices)_month_window_ms("05-2024")computes:start_ms = 1714521600000(2024-05-01 00:00:00.000 UTC)end_ms = 1717200000000(2024-06-01 00:00:00.000 UTC)
id status timestamp_ms In [start_ms, end_ms)? rootThreshold > 75.0? Result --- --------- ------------- ------------------------ --------------------- ------------ 101 "RUNNING" 1714521600000 Yes (== start_ms) 82.5 > 75.0 (Yes) COUNT (-> 1) 102 "RUNNING" 1715731200000 Yes (May 15 00:00:00 UTC) 75.0 > 75.0 (No, tie!) skip 103 "RUNNING" 1717199999000 Yes (May 31 23:59:59 UTC) 91.0 > 75.0 (Yes) COUNT (-> 2) 104 "RUNNING" 1717200000000 No (== end_ms, Jun 1!) -- skip 105 "STOPPED" 1715342400000 -- (fails status first) -- skipUnits
101and103pass all three gates, so the function returns2.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from datetime import datetime, timezone def _month_window_ms(date_str: str) -> Tuple[int, int]: """Return the half-open UTC window [start_ms, end_ms) for 'MM-YYYY' in epoch milliseconds.""" month_text, year_text = date_str.split("-") month = int(month_text) year = int(year_text) # Roll December forward to January of the next year so we never hardcode month lengths (28/29/30/31). if month == 12: next_year = year + 1 next_month = 1 else: next_year = year next_month = month + 1 # Pin both calendar instants to UTC; a naive datetime would use the machine's local time zone. start_utc = datetime(year, month, 1, tzinfo=timezone.utc) end_utc = datetime(next_year, next_month, 1, tzinfo=timezone.utc) # .timestamp() returns seconds since 1970-01-01 UTC; multiply by 1000 to match device millisecond timestamps. start_ms = int(start_utc.timestamp()) * 1000 end_ms = int(end_utc.timestamp()) * 1000 return start_ms, end_ms def num_devices(status_query: str, threshold: float, date_str: str, devices: List[Dict]) -> int: # Phase 1: Compute the target month's [start_ms, end_ms) window once up front, # e.g. '05-2024' -> (1714521600000, 1717200000000). start_ms, end_ms = _month_window_ms(date_str) # Phase 2: Scan each device dictionary and keep only devices passing all three checks. matching_count = 0 for device in devices: # 1. Exact status match (the input list can still contain other statuses like 'STOPPED'). if device["status"] != status_query: continue # 2. Half-open UTC month check: include start_ms (>=), exclude the next month's first ms (<). timestamp_ms = device["timestamp"] if timestamp_ms < start_ms or timestamp_ms >= end_ms: continue # 3. Strict '>' comparison: a rootThreshold equal to `threshold` does not qualify. root_threshold = device["operatingParams"]["rootThreshold"] if root_threshold > threshold: matching_count += 1 return matching_count✅ Submit now — all tests should pass.
Intuition & how it works
Think of filtering the device logs like checking visitors through three turnstiles in a row: first check the badge type (status), second check whether the arrival timestamp falls between two pre-marked fenceposts for the start of this month and the start of next month, and third check whether the sensor's rootThreshold clears a strict height bar (> threshold). Because every device timestamp is recorded in milliseconds since the Unix epoch (00:00:00 on January 1, 1970 in UTC, the universal reference time zone that never shifts for daylight saving or local location), we can convert "MM-YYYY" once into a half-open interval [start_ms, end_ms) — a range that includes its left endpoint start_ms (>=) and excludes its right endpoint end_ms (<).
Why does the naive date-conversion or end-of-month approach run into trouble? Converting every device's timestamp into a datetime object inside the loop does unnecessary date math on every record, and forgetting tz=timezone.utc makes Python interpret timestamps in the server's local time zone, pushing devices near midnight into the adjacent month. Trying to compute a closed end-of-month timestamp like 23:59:59 is equally fragile because it drops milliseconds like 23:59:59.500 and forces manual day-count rules for 28-, 29-, 30-, and 31-day months.
Walk through Example 1 (status_query = "RUNNING", threshold = 75.0, date_str = "05-2024"):
- May 2024 starts at 1714521600000 ms (2024-05-01 00:00:00 UTC) and ends right before 1717200000000 ms (2024-06-01 00:00:00 UTC).
- Unit 101 ("RUNNING", 1714521600000, rootThreshold = 82.5): matches status, equals start_ms (inside window), and 82.5 > 75.0 -> matching_count = 1.
- Unit 102 ("RUNNING", 1715731200000, rootThreshold = 75.0): inside May, but 75.0 > 75.0 is false -> skipped.
- Unit 103 ("RUNNING", 1717199999000, rootThreshold = 91.0): inside May and 91.0 > 75.0 -> matching_count = 2.
- Unit 104 ("RUNNING", 1717200000000, rootThreshold = 95.0): equals end_ms (already June 1) -> skipped.
- Unit 105 ("STOPPED", 1715342400000, rootThreshold = 88.0): status is "STOPPED" -> skipped. Return 2.
Complexity
- Time:
O(n), wherenislen(devices). Computing(start_ms, end_ms)fromdate_strtakes constantO(1)calendar work once before the loop, and the loop performs at most threeO(1)dictionary lookups and comparisons per device. (When fetching over a live HTTP service with pagination — splitting a large result list across numbered response pages — network round-trips across theppages takeO(p)HTTP requests and dominate wall-clock time.) - Space:
O(1)extra space, because we only store the two integer window bounds and the integer countermatching_countregardless of how many devices are scanned.
Edge cases
- Empty
deviceslist ([]): the loop does zero iterations and returns0. - Exact millisecond boundaries:
timestamp == start_ms(00:00:00.000 UTCon day 1) is counted, whereastimestamp == start_ms - 1andtimestamp == end_ms(00:00:00.000 UTCon day 1 of next month) are excluded. - December rollover (
"12-2024"):month == 12advances cleanly to(2025, 1)instead of crashing on an invalid month13. - Leap vs. non-leap February (
"02-2024"vs."02-2023"): both end at March 1 (2024-03-01vs.2023-03-01), so February 29 is automatically included in 2024 without leap-year formulas. - Same month in a different year: a December 2023 timestamp falls far below
start_msfor"12-2024"and is rejected. - Fractional and negative thresholds:
rootThreshold > thresholdhandles floats (25.6 > 25.5) and negatives (-0.5 > -1), while still rejecting exact ties (75.0 > 75.0and-1 > -1). - Mixed statuses in
devices: records with other statuses in the passed list are filtered out bydevice["status"] != status_query.
Common mistakes
- Using naive
datetimeobjects (local time instead of UTC):datetime(year, month, 1).timestamp()ordatetime.fromtimestamp(ts / 1000)withouttz=timezone.utcshifts the month boundary by the host machine's UTC offset. That bug passes on a UTC server and silently fails inUTC-5orUTC+5:30. - Mixing up seconds and milliseconds: forgetting
* 1000compares millisecond device timestamps (~1.7 * 10^12) against second boundaries (~1.7 * 10^9), matching zero devices; conversely, passing raw milliseconds tofromtimestampraisesValueError: year ... is out of range. - Using
>=instead of strict>onthreshold: the problem specifiesrootThreshold > threshold, so a tie like75.0against75.0must not be counted. - Parsing
"MM-YYYY"as"YYYY-MM":date_strputs the two-digit month before the four-digit year. - Off-by-one page loop in the live HTTP version: pages are 1-indexed (
1 .. total_pagesinclusive), sorange(1, total_pages)misses the final page.
Follow-up questions
- How would you retrieve and count matching records across all pages of a live HTTP endpoint? Request page
1first, readtotal_pagesfrom the JSON payload, and looppagefrom1throughtotal_pagesinclusive, accumulatingnum_devices(...)on each page's"data"array so you never hold the entire dataset in memory at once. Always encode query parameters withurllib.parse.urlencodeso statuses containing spaces or special characters do not break the URL, and stop cleanly iftotal_pages == 0:
```python import json from urllib.parse import urlencode from urllib.request import urlopen
def count_devices_from_api(base_url: str, status_query: str, threshold: float, date_str: str) -> int: total_matching = 0 page = 1 total_pages = 1 while page <= total_pages: query = urlencode({"status": status_query, "page": page}) with urlopen(f"{base_url}?{query}", timeout=10) as response: payload = json.load(response) total_matching += num_devices(status_query, threshold, date_str, payload["data"]) total_pages = payload["total_pages"] page += 1 return total_matching ```
- How would you make a multi-page API client fast and resilient against network failures or concurrent inserts? Once page
1revealstotal_pages, pages2 .. total_pagesare independent and can be fetched concurrently with a bounded thread pool (such asThreadPoolExecutor(max_workers=8)). Attach a per-request timeout and retry transient network errors,5xxresponses, or429 Too Many Requestsusing exponential backoff (doubling the wait time between retries, plus a small random jitter, so retrying clients do not stampede the server). If new devices are inserted while you paginate, numbered pages can shift and duplicate or skip items; asking the API for cursor pagination (passing back an opaque bookmark token pointing to the last seen record) or a point-in-time snapshot fixes that drift. - What changes if the target month must be evaluated in a specific regional time zone such as America/Los_Angeles rather than UTC? Only
_month_window_msneeds to change: replacetimezone.utcwithZoneInfo("America/Los_Angeles")from Python's standardzoneinfomodule when constructingstartandend. Their.timestamp() * 1000values still convert cleanly into universal epoch milliseconds, automatically accounting for 23-hour spring-forward and 25-hour fall-back daylight-saving days without touching any device record.
Follow-up questions
- How would you retrieve and count matching records across all pages of a live HTTP endpoint?
- How would you make a multi-page API client fast and resilient against network failures or concurrent inserts?
- What changes if the target month must be evaluated in a specific regional time zone such as America/Los_Angeles rather than UTC?
Similar questions
- Sum Lightest Weights Under Neighbor Deletions
- Optimal Worker Count Under Quadratic Merge Overhead
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months