Paginated Sensor-Alert Filter with Validation
Arrays & HashingAuto-graded · 20 test casesLast updated
Tests ability to validate, filter, sort, and paginate structured records while handling malformed entries and boundary conditions correctly.
Background
You are building a monitoring dashboard for an industrial sensor network. Each sensor periodically reports a pressure reading. Your job is to retrieve all sensors whose readings meet an alert threshold and return one page of results.
Task
Implement get_alert_records(records, page, page_size).
Input Format
records is a list of dictionaries, each with three fields:
{
"id": int, # unique sensor identifier
"systolic_bp": int, # recorded pressure value
"patient_dob": str # date string in "YYYY-MM-DD" format
}
Filtering Rule
Include a record if its systolic_bp is greater than or equal to 140.
Validation
Before filtering, inspect every entry:
- If
systolic_bpisNoneor missing, skip the entry. - If
patient_dobis not a string in the exact format"YYYY-MM-DD"representing a real calendar date, skip the entry. Strings like"2023-2-3"or"2021-02-29"must be rejected.
Skipped entries must not appear in data and must not count toward total.
Ordering and Pagination
- Sort all valid, matching entries by
idascending. - Treat
pageas 1-indexed. Return entries at positions[(page-1)*page_size, page*page_size)in the sorted list. - If the requested page is beyond the last entry, return an empty
datalist while still reporting the correcttotal.
Output Format
Return a dictionary with exactly these keys:
{
"data": list[int], # ids of matching entries on this page, in ascending id order
"total": int, # total number of valid matching entries across all pages
"page": int # the page number that was requested
}
If page < 1 or page_size <= 0, return {"data": [], "total": <correct total>, "page": page}.
Constraints
0 <= len(records) <= 10_000- Each
idis a positive integer; treat duplicate ids as independent entries (stable sort preserves their relative input order). systolic_bp, when present and valid, is a non-negative integer.1 <= page_size <= 1_000for well-formed calls.- The function must not raise an exception for any input matching the types above.
Examples
Example 1
Input: get_alert_records([{'id': 101, 'systolic_bp': 145, 'patient_dob': '1980-05-20'}, {'id': 102, 'systolic_bp': 140, 'patient_dob': '1990-01-01'}, {'id': 103, 'systolic_bp': 130, 'patient_dob': '1975-12-12'}], 1, 2)
Output: {'data': [101, 102], 'total': 2, 'page': 1}
Example 2
Input: get_alert_records([{'id': 3, 'systolic_bp': 160, 'patient_dob': '1970-03-10'}, {'id': 1, 'systolic_bp': 141, 'patient_dob': '1985-07-22'}, {'id': 2, 'systolic_bp': 139, 'patient_dob': '1992-11-01'}], 1, 1)
Output: {'data': [1], 'total': 2, 'page': 1}
Example 3
Input: get_alert_records([{'id': 10, 'systolic_bp': 140, 'patient_dob': '2000-01-01'}, {'id': 11, 'systolic_bp': 140, 'patient_dob': '2001-02-03'}, {'id': 12, 'systolic_bp': 141, 'patient_dob': '2002-03-04'}], 2, 2)
Output: {'data': [12], 'total': 3, 'page': 2}
Hints
Hint 1
Work in a strict pipeline: validate first, then filter, then sort, then slice. Mixing these steps leads to a `total` that disagrees with the returned `data`.
Hint 2
Use `date.fromisoformat()` to parse `patient_dob`, but also verify the parsed date formats back to exactly the original string — this rejects inputs like `'2023-2-3'` that `fromisoformat` would otherwise accept.
Hint 3
Compute `total` from the full filtered list before slicing. The slice index is `(page - 1) * page_size`; Python's slice syntax handles out-of-range indices gracefully, so no extra bounds check is needed for `data` — but do handle the `page < 1 or page_size <= 0` guard separately.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution runs as four sequential stages, each with one responsibility.
1. Validate
Iterate over every record and reject it if either field is unusable:
systolic_bpisNoneor absent — skip.patient_dobfails the date check — skip.
For the date, date.fromisoformat() is the parser, but it is too lenient on its own: it accepts "2023-2-3" with single-digit month and day. The fix is a round-trip check — parse the string, format it back with .isoformat(), and confirm the result equals the original. That rejects any string not in the exact YYYY-MM-DD shape and also catches impossible dates like "2021-02-29", which raises ValueError directly.
2. Filter
A record passes if systolic_bp >= 140. The threshold is inclusive because the sample cases confirm it: a record with exactly 140 appears in the expected output.
3. Sort
Sort all passing records by id ascending. Sorting the full filtered list before slicing is what makes pagination deterministic — every record has a fixed global position regardless of which page is requested.
4. Paginate
Compute total from the sorted list length, then slice [start : start + page_size] where start = (page - 1) * page_size. Python's slice clamps out-of-range indices automatically, so a page past the end naturally returns [] with no extra condition. The only explicit guard needed covers page < 1 or page_size <= 0, which would produce a meaningless or negative start index.
Why it is correct
- Sorting before slicing guarantees page 2 always follows page 1 in the same global order, with no gaps or repeated records.
- Computing
totalafter validation and filtering but before slicing means it always matches the sum across all pages — it is never inflated by invalid entries. - The round-trip date check is both necessary and sufficient: it catches malformed shapes the parser would otherwise accept.
Complexity
- Time: O(n) to validate and filter, O(m log m) to sort the m matching records, O(page_size) for the final slice.
- Space: O(m) for the filtered list, O(page_size) for the output ids.
Reference Solution
from datetime import date
from typing import Dict, List
def get_alert_records(records: List[Dict], page: int, page_size: int) -> Dict:
# Threshold is inclusive: systolic_bp >= 140 triggers an alert.
THRESHOLD = 140
matching = []
for record in records:
systolic_bp = record.get("systolic_bp")
patient_dob = record.get("patient_dob")
# Validate systolic_bp: must be present and not None.
if systolic_bp is None:
continue
# Validate patient_dob: must be a real YYYY-MM-DD date string.
# fromisoformat alone accepts "2023-2-3"; the round-trip check rejects it.
try:
parsed = date.fromisoformat(patient_dob)
if parsed.isoformat() != patient_dob:
raise ValueError
except (TypeError, ValueError):
continue
if systolic_bp >= THRESHOLD:
matching.append(record)
# Sort by id ascending; Python's sort is stable so equal ids preserve input order.
matching.sort(key=lambda r: r["id"])
total = len(matching)
# Guard against nonsensical pagination parameters.
if page < 1 or page_size <= 0:
return {"data": [], "total": total, "page": page}
start = (page - 1) * page_size
page_ids = [r["id"] for r in matching[start:start + page_size]]
return {"data": page_ids, "total": total, "page": page}