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 since 1970-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" (int or float) 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:

  1. Exact state match: device["status"] == status_query (case-sensitive).
  2. UTC registration month: device["timestamp"], interpreted in UTC, falls inside the calendar month and year specified by date_str ("MM-YYYY").
  3. Strict threshold check: device["operatingParams"]["rootThreshold"] > threshold (records equal to threshold do 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^5
  • date_str always follows "MM-YYYY" with "01" <= MM <= "12" and 1970 <= YYYY <= 2100.
  • device["timestamp"] is a non-negative integer in UTC epoch milliseconds.
  • threshold and device["operatingParams"]["rootThreshold"] are int or float values in [-10^9, 10^9].
  • status_query and device["status"] are non-empty strings.

Step-by-step walkthrough

  1. Understand the inputs and the three filter rules

    Each item in devices is 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:

    1. Status matches: device["status"] == status_query. Even when records originate from a filtered endpoint, the devices list passed to num_devices can contain mixed statuses (Example 1 includes a "STOPPED" record), so we must verify the status explicitly.
    2. Registered in the target UTC month: device["timestamp"] (in UTC milliseconds) falls inside the calendar month and year given by date_str in "MM-YYYY" format (such as "05-2024" for May 2024).
    3. Strictly above threshold: device["operatingParams"]["rootThreshold"] > threshold. Equality does not count.
  2. Key idea: turn the month into a half-open UTC window

    A tempting first approach is to convert every device's timestamp into a datetime object and check dt.month == month and dt.year == year. That works if done carefully, but it builds a new datetime object on every iteration and invites a classic bug: calling datetime.fromtimestamp(...) without tz=timezone.utc uses the machine's local time zone, shifting devices near midnight into the wrong month.

    Instead, we can convert date_str once into two integers [start_ms, end_ms):

    • start_ms: 00:00:00.000 UTC on day 1 of the target month (included).
    • end_ms: 00:00:00.000 UTC on 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_ms gives 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 at 23:59:59.500 on the last day of the month, which happens when people hardcode 23:59:59 as an end time.

  3. Write the month-window helper

    To compute (start_ms, end_ms) from "MM-YYYY":

    1. Split date_str on "-" and convert both pieces with int(...) (int("05") becomes 5).
    2. Find the next month: if month == 12, the next month is January (1) of year + 1; otherwise it is month + 1 of the same year.
    3. Construct both datetime objects with tzinfo=timezone.utc. Leaving out tzinfo would make .timestamp() interpret the date in local system time!
    4. Multiply int(dt.timestamp()) by 1000 because .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
    
  4. Write the device-filtering loop

    With (start_ms, end_ms) precomputed, filtering devices is a clean single pass using three guard checks:

    • Skip if device["status"] != status_query.
    • Skip if timestamp_ms < start_ms (too early) or timestamp_ms >= end_ms (already in the next month or later).
    • Increment matching_count only if device["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
    
  5. 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)    --                      skip
    

    Units 101 and 103 pass all three gates, so the function returns 2.

  6. 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), where n is len(devices). Computing (start_ms, end_ms) from date_str takes constant O(1) calendar work once before the loop, and the loop performs at most three O(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 the p pages take O(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 counter matching_count regardless of how many devices are scanned.

Edge cases

  • Empty devices list ([]): the loop does zero iterations and returns 0.
  • Exact millisecond boundaries: timestamp == start_ms (00:00:00.000 UTC on day 1) is counted, whereas timestamp == start_ms - 1 and timestamp == end_ms (00:00:00.000 UTC on day 1 of next month) are excluded.
  • December rollover ("12-2024"): month == 12 advances cleanly to (2025, 1) instead of crashing on an invalid month 13.
  • Leap vs. non-leap February ("02-2024" vs. "02-2023"): both end at March 1 (2024-03-01 vs. 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_ms for "12-2024" and is rejected.
  • Fractional and negative thresholds: rootThreshold > threshold handles floats (25.6 > 25.5) and negatives (-0.5 > -1), while still rejecting exact ties (75.0 > 75.0 and -1 > -1).
  • Mixed statuses in devices: records with other statuses in the passed list are filtered out by device["status"] != status_query.

Common mistakes

  • Using naive datetime objects (local time instead of UTC): datetime(year, month, 1).timestamp() or datetime.fromtimestamp(ts / 1000) without tz=timezone.utc shifts the month boundary by the host machine's UTC offset. That bug passes on a UTC server and silently fails in UTC-5 or UTC+5:30.
  • Mixing up seconds and milliseconds: forgetting * 1000 compares millisecond device timestamps (~1.7 * 10^12) against second boundaries (~1.7 * 10^9), matching zero devices; conversely, passing raw milliseconds to fromtimestamp raises ValueError: year ... is out of range.
  • Using >= instead of strict > on threshold: the problem specifies rootThreshold > threshold, so a tie like 75.0 against 75.0 must not be counted.
  • Parsing "MM-YYYY" as "YYYY-MM": date_str puts 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_pages inclusive), so range(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 1 first, read total_pages from the JSON payload, and loop page from 1 through total_pages inclusive, accumulating num_devices(...) on each page's "data" array so you never hold the entire dataset in memory at once. Always encode query parameters with urllib.parse.urlencode so statuses containing spaces or special characters do not break the URL, and stop cleanly if total_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 1 reveals total_pages, pages 2 .. total_pages are independent and can be fetched concurrently with a bounded thread pool (such as ThreadPoolExecutor(max_workers=8)). Attach a per-request timeout and retry transient network errors, 5xx responses, or 429 Too Many Requests using 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_ms needs to change: replace timezone.utc with ZoneInfo("America/Los_Angeles") from Python's standard zoneinfo module when constructing start and end. Their .timestamp() * 1000 values 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

Similar questions

More Kneron interview questions

All 3 Kneron questions →