Hardware Device Registry: Validation, Active Tallies, and Bulk Transitions
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
You are maintaining an in-memory hardware inventory service built around ALLOWED_STATUSES, Device, RegistrationError, and DeviceRegistry:
ALLOWED_STATUSES = {
"sensor": {"ACTIVE", "INACTIVE", "MAINTENANCE"},
"camera": {"ACTIVE", "INACTIVE", "FAULTY"},
"gateway": {"ACTIVE", "MAINTENANCE", "FAULTY"},
}
Each Device(device_id, device_type, status, registered_at) instance records those four attributes and initializes last_maintenance_at = registered_at and failure_count = 0. External monitoring code may subsequently update last_maintenance_at, failure_count, or status directly on stored Device objects. DeviceRegistry stores registered hardware in self.devices (dict mapping device_id -> Device).
Complete the following four tasks in DeviceRegistry:
-
Fix
is_valid_status(self, device_type, status) -> bool(used byadd_device):- The starter implementation mistakenly scans every set in
ALLOWED_STATUSES.values()while ignoringdevice_type, causingadd_deviceto accept statuses belonging to other hardware categories as well as unrecognizeddevice_typestrings. - Update
is_valid_statusso it returnsTrueif and only if bothdevice_typeandstatusarestrinstances,device_typeis an exact key inALLOWED_STATUSES, andstatusbelongs toALLOWED_STATUSES[device_type]. Non-string or unhashable arguments (such asNone, lists, or sets) must returnFalsecleanly without raisingTypeError. add_device(self, device) -> boolmust continue returningFalse(leavingself.devicesunchanged) whenis_valid_statusrejects the pair, and storingself.devices[device.device_id] = devicewhile returningTrueotherwise.
- The starter implementation mistakenly scans every set in
-
Implement
register_device(self, device_id, device_type, status, registered_at) -> Device:- Validate arguments in the exact order below, raising
RegistrationError(reason, message)(aValueErrorsubclass whose.reasonattribute holds the machine-readable code) on the first failing check without mutatingself.devices:"INVALID_ID"—device_idis not astror equals""."UNKNOWN_TYPE"—device_typeis not astror is absent fromALLOWED_STATUSES."STATUS_NOT_ALLOWED"—statusis not astror is disallowed fordevice_typebyALLOWED_STATUSES."INVALID_TIME"—registered_atis not anint(boolvalues such asTrue/Falseandfloatvalues must be rejected)."NEGATIVE_TIME"—registered_at < 0(0and positive integers are permitted)."DUPLICATE_ID"—device_idalready exists inself.devices(even when every field matches the stored record).
- When all six checks succeed, construct
Device(device_id, device_type, status, registered_at), insert it underself.devices[device_id], and return the newDevice.
- Validate arguments in the exact order below, raising
-
Implement
count_active_by_type(self) -> Dict[str, int]:- Return a dictionary mapping each
device_typeto the count of currently stored devices whosestatus == "ACTIVE". - Omit any
device_typewhose active count is0, and insert dictionary keys in ascending alphabetical order.
- Return a dictionary mapping each
-
Implement
bulk_update_status(self, now, maintenance_interval, failure_threshold) -> int:- First validate parameters:
now,maintenance_interval, andfailure_thresholdmust each be numeric (intorfloat, rejectingbooland non-numbers), withmaintenance_interval > 0andfailure_threshold > 0; otherwise raiseValueErrorbefore modifying any device. - Only devices currently in status
"ACTIVE"are eligible ("INACTIVE","MAINTENANCE", and"FAULTY"devices remain untouched). - For each
"ACTIVE"device, evaluate candidate target statuses in strict priority order:"FAULTY"ifdevice.failure_count >= failure_threshold."MAINTENANCE"ifnow - device.last_maintenance_at >= maintenance_interval.
- Transition the device to the first triggered target status permitted for its
device_typeinALLOWED_STATUSES(falling through to rule 2 if rule 1 triggers a disallowed status, or leaving the device"ACTIVE"if no triggered target is allowed). Return the integer count of devices whose status changed.
- First validate parameters:
Examples
Example 1
registry = DeviceRegistry()
rejected = registry.add_device(Device("gw-04", "gateway", "INACTIVE", 250))
# rejected -> False ("gateway" permits {"ACTIVE", "MAINTENANCE", "FAULTY"}, not "INACTIVE")
dev = registry.register_device("gw-04", "gateway", "ACTIVE", 250)
# dev.registered_at == 250, dev.last_maintenance_at == 250, dev.failure_count == 0
# Raises RegistrationError with reason == "STATUS_NOT_ALLOWED" (checked before negative time & duplicate ID)
registry.register_device("gw-04", "sensor", "FAULTY", -10)
Walk-through: "INACTIVE" exists on sensors and cameras, not gateways, so the fixed is_valid_status returns False and add_device leaves registry.devices empty. Registering "gw-04" as an "ACTIVE" "gateway" at timestamp 250 succeeds. A subsequent malformed call ("gw-04", "sensor", "FAULTY", -10) fails check 3 ("STATUS_NOT_ALLOWED") before reaching "NEGATIVE_TIME" or "DUPLICATE_ID", leaving "gw-04" unchanged.
Example 2
registry = DeviceRegistry()
registry.register_device("sen-10", "sensor", "ACTIVE", 50)
registry.register_device("sen-20", "sensor", "MAINTENANCE", 60)
registry.register_device("gw-10", "gateway", "ACTIVE", 70)
registry.register_device("gw-20", "gateway", "ACTIVE", 80)
registry.register_device("cam-10", "camera", "INACTIVE", 90)
counts = registry.count_active_by_type()
# counts -> {"gateway": 2, "sensor": 1}
Walk-through: Two gateways and one sensor currently hold status "ACTIVE". Because "cam-10" is "INACTIVE", "camera" has zero active units and is omitted entirely; the remaining keys are inserted in sorted order ["gateway", "sensor"].
Example 3
registry = DeviceRegistry()
# Helper setup: register each device at t=0, then set (last_maintenance_at, failure_count):
# "gw-10": ("gateway", "ACTIVE", last_maintenance_at=300, failure_count=3) -> FAULTY
# "sen-10": ("sensor", "ACTIVE", last_maintenance_at=350, failure_count=4) -> MAINTENANCE
# "sen-20": ("sensor", "ACTIVE", last_maintenance_at=500, failure_count=5) -> ACTIVE (unchanged)
# "cam-10": ("camera", "ACTIVE", last_maintenance_at=100, failure_count=0) -> ACTIVE (unchanged)
# "cam-20": ("camera", "ACTIVE", last_maintenance_at=550, failure_count=2) -> FAULTY
# "gw-20": ("gateway", "FAULTY", last_maintenance_at=0, failure_count=8) -> FAULTY (ineligible)
changed = registry.bulk_update_status(now=600, maintenance_interval=200, failure_threshold=2)
# changed -> 3
Walk-through: At now = 600 with maintenance_interval = 200 and failure_threshold = 2, "gw-10" triggers both rules and picks higher-priority "FAULTY". "sen-10" triggers "FAULTY" first, sees "sensor" disallows "FAULTY", and falls through to "MAINTENANCE" (600 - 350 = 250 >= 200). "sen-20" disallows "FAULTY" and is not yet overdue (100 < 200), "cam-10" disallows "MAINTENANCE", "cam-20" hits 2 >= 2 ("FAULTY"), and "gw-20" is skipped because it is not "ACTIVE"—giving 3 transitions in total.
Constraints
- All string comparisons for
device_typeandstatusare strictly case-sensitive. - Any failed
register_deviceorbulk_update_statuscall must leaveself.devicesand all storedDeviceobjects completely unmodified. registered_atmust be an exactint(>= 0), rejectingboolandfloat.now,maintenance_interval, andfailure_thresholdacceptintorfloat(rejectingbool), withmaintenance_interval > 0andfailure_threshold > 0.
Step-by-step walkthrough
Settle requirements and API contracts before coding
This exercise builds four incremental changes on a single
DeviceRegistrymodule:- Find and fix a validation bug exposed by a failing test.
- Add
register_devicewith full input validation. - Add
count_active_by_typeexcluding zero-count types. - Add
bulk_update_statusdriven by failure count and maintenance age.
Because progressive business-logic interviews intentionally leave edge behavior open, lock down explicit, testable contracts first:
- Error reporting: Keep
add_devicereturningTrue/Falseso existing callers and tests do not break. Have the newregister_deviceraiseRegistrationError(reason, message)(aValueErrorsubclass with a machine-readablereasonattribute like"DUPLICATE_ID") so callers know which rule failed without fragile string matching. - Exact case matching:
"Sensor"and"active"are rejected rather than silently upper/lowercased, surfacing bad upstream data immediately. - Timestamps and duplicates:
registered_atmust be a non-negativeint(boolandfloatare rejected; future timestamps are allowed because the registry holds no wall clock). Re-registering an existingdevice_idalways raises"DUPLICATE_ID", even with identical fields. - Single-threaded core, deterministic output: Assume single-threaded calls for the base class (multi-thread safety is handled via a lock in follow-ups), and insert keys in sorted order in
count_active_by_type.
Part 1: Trace the status-validation bug to the root cause
Start from Example 1's rejected call and trace backwards line by line:
call: gateway = Device("gw-04", "gateway", "INACTIVE", 250) registry.add_device(gateway) --> returned True in starter (expected False!) | v add_device: calls self.is_valid_status("gateway", "INACTIVE") | v buggy code: for statuses in ALLOWED_STATUSES.values(): if status in statuses: --> "INACTIVE" is in sensor's set -> returns True!Look at the method signature
def is_valid_status(self, device_type, status):—the parameterdevice_typeis never used! Instead of checking whetherstatusis valid for this specificdevice_type, the loop checks whether any device type in the entire configuration map allowsstatus.Because
device_typeis ignored, the exact same bug lets two whole classes of invalid devices slip intoself.devices:- Cross-type statuses:
"gateway"with"INACTIVE"(from"sensor"/"camera"),"sensor"with"FAULTY"(from"camera"/"gateway"), and"camera"with"MAINTENANCE"(from"sensor"/"gateway"). - Completely unknown device types:
Device("prt-1", "printer", "ACTIVE", 0)is accepted because"ACTIVE"exists in"sensor", and"printer"is never looked up!
- Cross-type statuses:
Part 1: Fix is_valid_status with a minimal, safe lookup
Instead of scanning
ALLOWED_STATUSES.values(), look upALLOWED_STATUSES.get(device_type)directly. Checkingisinstance(..., str)first also prevents unhashable inputs (like["camera"]) from crashing dictionary or set lookups withTypeError:def is_valid_status(self, device_type, status): # Reject non-strings first so unhashable values (like lists or sets) return False # cleanly instead of crashing dict/set lookups with TypeError. if not isinstance(device_type, str) or not isinstance(status, str): return False allowed_for_type = ALLOWED_STATUSES.get(device_type) if allowed_for_type is None: return False return status in allowed_for_typeLeave
add_deviceuntouched so we do not break existing callers that rely on its boolean return value or overwrite behavior. Pin the fix with regression tests covering cross-type statuses (sensor/FAULTY,gateway/INACTIVE,camera/MAINTENANCE), unknown types (printer/ACTIVE), unknown statuses (camera/BROKEN), unhashable types, and valid pairs (camera/FAULTY,sensor/MAINTENANCE).Part 2: Order checks for atomic, predictable registration
Atomicity means an operation either succeeds completely or leaves zero changes behind. In
register_device, atomicity is guaranteed by running every validation check before constructingDeviceor writing toself.devices.The order of those six checks also matters for two subtle reasons:
- Validate types before hash lookups: If a caller passes
device_id = ["s-9"]and we checkdevice_id in self.devicesfirst, Python raisesTypeError: unhashable type: 'list'instead of our cleanRegistrationError("INVALID_ID", ...). - Reject
boolbeforeint, and check state last: In Python,boolsubclassesint(isinstance(True, int)evaluates toTrue!), soisinstance(registered_at, bool)must be checked first. Running theDUPLICATE_IDlookup last guarantees malformed arguments always report the same input error regardless of what is currently stored.
Check order in _validate_registration: 1. not isinstance(device_id, str) or device_id == "" --> RegistrationError("INVALID_ID") 2. not isinstance(device_type, str) or not in map --> RegistrationError("UNKNOWN_TYPE") 3. not isinstance(status, str) or not valid for type --> RegistrationError("STATUS_NOT_ALLOWED") 4. isinstance(registered_at, bool) or not int --> RegistrationError("INVALID_TIME") 5. registered_at < 0 --> RegistrationError("NEGATIVE_TIME") 6. device_id in self.devices --> RegistrationError("DUPLICATE_ID") --> All passed: create Device, store in self.devices[device_id], return Device- Validate types before hash lookups: If a caller passes
Part 2: Implement RegistrationError and register_device
Putting validation in
_validate_registrationkeepsregister_devicefour lines long and crystal clear:class RegistrationError(ValueError): """Raised by register_device; `reason` names the check that failed.""" def __init__(self, reason: str, message: str) -> None: super().__init__(message) self.reason = reasondef register_device(self, device_id, device_type, status, registered_at) -> Device: # Validate every field and uniqueness check BEFORE creating or storing anything # so any failed call leaves self.devices completely untouched (atomic rejection). self._validate_registration(device_id, device_type, status, registered_at) device = Device(device_id, device_type, status, registered_at) self.devices[device_id] = device return device def _validate_registration(self, device_id, device_type, status, registered_at): # 1-3: Validate string types and allowed-map membership before any hash lookup # on self.devices so malformed inputs raise RegistrationError, never TypeError. if not isinstance(device_id, str) or device_id == "": raise RegistrationError("INVALID_ID", f"device_id must be a non-empty string, got {device_id!r}") if not isinstance(device_type, str) or device_type not in ALLOWED_STATUSES: raise RegistrationError("UNKNOWN_TYPE", f"unknown device type {device_type!r}") if not isinstance(status, str) or not self.is_valid_status(device_type, status): raise RegistrationError("STATUS_NOT_ALLOWED", f"status {status!r} is not allowed for {device_type!r}") # 4-5: In Python, bool is a subclass of int (isinstance(True, int) is True), # so explicitly reject bool before checking isinstance(..., int). if isinstance(registered_at, bool) or not isinstance(registered_at, int): raise RegistrationError("INVALID_TIME", f"registered_at must be an int, got {registered_at!r}") if registered_at < 0: raise RegistrationError("NEGATIVE_TIME", f"registered_at must be >= 0, got {registered_at}") # 6: Check duplicate ID last so malformed inputs always fail with the same # input-validation reason regardless of current registry state. if device_id in self.devices: raise RegistrationError("DUPLICATE_ID", f"device {device_id!r} is already registered")Part 3: Count active devices per type while omitting zeros
To omit device types with zero active devices naturally, iterate over
self.devices.values()rather than starting fromALLOWED_STATUSES.keys(). A device type only entersactive_countswhen we actually encounter an"ACTIVE"device of that type—so zero-count types are never created in the first place.Why scan on demand (
O(n)overndevices) instead of maintaining a cachedactive_countsdictionary on every write? BecauseDevice.statusis a plain public attribute (device.status = "ACTIVE"). Just as external code mutateslast_maintenance_atandfailure_countdirectly onDeviceinstances, direct assignments todevice.statuswould bypass the registry and silently desynchronize cached counters. Scanningself.devicesis always accurate and fast.def count_active_by_type(self) -> Dict[str, int]: # active_counts: {device_type: count of ACTIVE devices}, accumulated from stored # devices so types with zero active devices are omitted automatically. active_counts = {} for device in self.devices.values(): if device.status == "ACTIVE": device_type = device.device_type active_counts[device_type] = active_counts.get(device_type, 0) + 1 # Insert keys in sorted order so iteration and string output are deterministic. sorted_counts = {} for device_type in sorted(active_counts): sorted_counts[device_type] = active_counts[device_type] return sorted_countsPart 4: Bulk status update with priority and per-type fallback
Pin down clear, conflict-free rules for
bulk_update_status(now, maintenance_interval, failure_threshold):- Parameter guard: Reject non-numeric/boolean arguments or
maintenance_interval <= 0orfailure_threshold <= 0withValueErrorbefore touching any device. - Eligibility: Only devices currently in
"ACTIVE"are eligible ("INACTIVE","MAINTENANCE", and"FAULTY"devices are already out of normal service). - Priority and per-type fallback:
- Check failures first (
device.failure_count >= failure_threshold->"FAULTY"), because hardware failure is more urgent than routine service. - Crucial interaction with
ALLOWED_STATUSES:"sensor"does not allow"FAULTY", and"camera"does not allow"MAINTENANCE". If a rule triggers a target status thatis_valid_statusrejects for that device's type, fall through to the next triggered rule instead of writing an illegal status! For example, an"ACTIVE"sensor that is both failing and overdue cannot become"FAULTY", so it falls through and becomes"MAINTENANCE".
- Check failures first (
device_type failing (>= T)? overdue (>= I)? allowed statuses chosen target gateway yes yes ACTIVE, MAINTENANCE, FAULTY "FAULTY" (priority 1 wins) sensor yes yes ACTIVE, INACTIVE, MAINTENANCE "MAINTENANCE" ("FAULTY" disallowed -> falls through) sensor yes no ACTIVE, INACTIVE, MAINTENANCE None ("FAULTY" disallowed, not overdue) camera no yes ACTIVE, INACTIVE, FAULTY None ("MAINTENANCE" disallowed)def bulk_update_status(self, now, maintenance_interval, failure_threshold) -> int: # Validate threshold parameters up front so an invalid call mutates zero devices. if ( isinstance(now, bool) or not isinstance(now, (int, float)) or isinstance(maintenance_interval, bool) or not isinstance(maintenance_interval, (int, float)) or isinstance(failure_threshold, bool) or not isinstance(failure_threshold, (int, float)) ): raise ValueError("now, maintenance_interval, and failure_threshold must be numbers") if maintenance_interval <= 0 or failure_threshold <= 0: raise ValueError("maintenance_interval and failure_threshold must be positive") updated_count = 0 for device in self.devices.values(): new_status = self._choose_bulk_target(device, now, maintenance_interval, failure_threshold) # Count only genuine transitions where a valid target status differs from current status. if new_status is not None and new_status != device.status: device.status = new_status updated_count += 1 return updated_count def _choose_bulk_target(self, device, now, maintenance_interval, failure_threshold): """Return the highest-priority triggered status permitted for this device's type, or None.""" # Only currently ACTIVE devices are eligible; INACTIVE/MAINTENANCE/FAULTY stay untouched. if device.status != "ACTIVE": return None # Priority 1: failures reaching failure_threshold prefer "FAULTY". # If "FAULTY" is disallowed for this type (e.g., "sensor"), fall through to check maintenance. if device.failure_count >= failure_threshold: if self.is_valid_status(device.device_type, "FAULTY"): return "FAULTY" # Priority 2: elapsed time since last maintenance reaching maintenance_interval tries "MAINTENANCE". elapsed_since_maintenance = now - device.last_maintenance_at if elapsed_since_maintenance >= maintenance_interval: if self.is_valid_status(device.device_type, "MAINTENANCE"): return "MAINTENANCE" return None- Parameter guard: Reject non-numeric/boolean arguments or
Walk through Example 3 and assemble the full solution
Trace
bulk_update_status(now=600, maintenance_interval=200, failure_threshold=2)across the six devices from Example 3:id type before last_maint elapsed failures outcome gw-10 gateway ACTIVE 300 300 3 -> FAULTY (both trigger; FAULTY wins) sen-10 sensor ACTIVE 350 250 4 -> MAINTENANCE (sensor disallows FAULTY; falls through) sen-20 sensor ACTIVE 500 100 5 unchanged (sensor disallows FAULTY; not overdue) cam-10 camera ACTIVE 100 500 0 unchanged (camera disallows MAINTENANCE) cam-20 camera ACTIVE 550 50 2 -> FAULTY (failures == 2 hits boundary) gw-20 gateway FAULTY 0 600 8 unchanged (not ACTIVE -> ineligible)Exactly 3 devices (
gw-10,sen-10,cam-20) change status, so the call returns3. Calling it a second time immediately returns0because those 3 devices are no longer"ACTIVE".from typing import Dict # Configuration map: each known device_type -> set of valid status strings for that type. ALLOWED_STATUSES = { "sensor": {"ACTIVE", "INACTIVE", "MAINTENANCE"}, "camera": {"ACTIVE", "INACTIVE", "FAULTY"}, "gateway": {"ACTIVE", "MAINTENANCE", "FAULTY"}, } class RegistrationError(ValueError): """Raised by register_device; `reason` names the check that failed.""" def __init__(self, reason: str, message: str) -> None: super().__init__(message) self.reason = reason class Device: def __init__(self, device_id, device_type, status, registered_at): self.device_id = device_id self.device_type = device_type self.status = status self.registered_at = registered_at # New devices start with last maintenance at registration time and zero failures. self.last_maintenance_at = registered_at self.failure_count = 0 class DeviceRegistry: def __init__(self): # Primary store: maps device_id (str) -> Device instance. self.devices = {} def is_valid_status(self, device_type, status): # Reject non-strings first so unhashable values (like lists or sets) return False # cleanly instead of crashing dict/set lookups with TypeError. if not isinstance(device_type, str) or not isinstance(status, str): return False allowed_for_type = ALLOWED_STATUSES.get(device_type) if allowed_for_type is None: return False return status in allowed_for_type def add_device(self, device): if not self.is_valid_status(device.device_type, device.status): return False self.devices[device.device_id] = device return True def register_device(self, device_id, device_type, status, registered_at) -> Device: # Validate every field and uniqueness check BEFORE creating or storing anything # so any failed call leaves self.devices completely untouched (atomic rejection). self._validate_registration(device_id, device_type, status, registered_at) device = Device(device_id, device_type, status, registered_at) self.devices[device_id] = device return device def _validate_registration(self, device_id, device_type, status, registered_at): # 1-3: Validate string types and allowed-map membership before any hash lookup # on self.devices so malformed inputs raise RegistrationError, never TypeError. if not isinstance(device_id, str) or device_id == "": raise RegistrationError("INVALID_ID", f"device_id must be a non-empty string, got {device_id!r}") if not isinstance(device_type, str) or device_type not in ALLOWED_STATUSES: raise RegistrationError("UNKNOWN_TYPE", f"unknown device type {device_type!r}") if not isinstance(status, str) or not self.is_valid_status(device_type, status): raise RegistrationError("STATUS_NOT_ALLOWED", f"status {status!r} is not allowed for {device_type!r}") # 4-5: In Python, bool is a subclass of int (isinstance(True, int) is True), # so explicitly reject bool before checking isinstance(..., int). if isinstance(registered_at, bool) or not isinstance(registered_at, int): raise RegistrationError("INVALID_TIME", f"registered_at must be an int, got {registered_at!r}") if registered_at < 0: raise RegistrationError("NEGATIVE_TIME", f"registered_at must be >= 0, got {registered_at}") # 6: Check duplicate ID last so malformed inputs always fail with the same # input-validation reason regardless of current registry state. if device_id in self.devices: raise RegistrationError("DUPLICATE_ID", f"device {device_id!r} is already registered") def count_active_by_type(self) -> Dict[str, int]: # active_counts: {device_type: count of ACTIVE devices}, accumulated from stored # devices so types with zero active devices are omitted automatically. active_counts = {} for device in self.devices.values(): if device.status == "ACTIVE": device_type = device.device_type active_counts[device_type] = active_counts.get(device_type, 0) + 1 # Insert keys in sorted order so iteration and string output are deterministic. sorted_counts = {} for device_type in sorted(active_counts): sorted_counts[device_type] = active_counts[device_type] return sorted_counts def bulk_update_status(self, now, maintenance_interval, failure_threshold) -> int: # Validate threshold parameters up front so an invalid call mutates zero devices. if ( isinstance(now, bool) or not isinstance(now, (int, float)) or isinstance(maintenance_interval, bool) or not isinstance(maintenance_interval, (int, float)) or isinstance(failure_threshold, bool) or not isinstance(failure_threshold, (int, float)) ): raise ValueError("now, maintenance_interval, and failure_threshold must be numbers") if maintenance_interval <= 0 or failure_threshold <= 0: raise ValueError("maintenance_interval and failure_threshold must be positive") updated_count = 0 for device in self.devices.values(): new_status = self._choose_bulk_target(device, now, maintenance_interval, failure_threshold) # Count only genuine transitions where a valid target status differs from current status. if new_status is not None and new_status != device.status: device.status = new_status updated_count += 1 return updated_count def _choose_bulk_target(self, device, now, maintenance_interval, failure_threshold): """Return the highest-priority triggered status permitted for this device's type, or None.""" # Only currently ACTIVE devices are eligible; INACTIVE/MAINTENANCE/FAULTY stay untouched. if device.status != "ACTIVE": return None # Priority 1: failures reaching failure_threshold prefer "FAULTY". # If "FAULTY" is disallowed for this type (e.g., "sensor"), fall through to check maintenance. if device.failure_count >= failure_threshold: if self.is_valid_status(device.device_type, "FAULTY"): return "FAULTY" # Priority 2: elapsed time since last maintenance reaching maintenance_interval tries "MAINTENANCE". elapsed_since_maintenance = now - device.last_maintenance_at if elapsed_since_maintenance >= maintenance_interval: if self.is_valid_status(device.device_type, "MAINTENANCE"): return "MAINTENANCE" return None✅ Submit now — all tests should pass.
Intuition & how it works
Think of DeviceRegistry as an equipment check-in desk with a separate rulebook page for each hardware type: sensors, cameras, and gateways each permit their own subset of statuses, and every check-in or automated sweep must consult that specific device type's page before recording any state change. By validating every rule up front before touching self.devices, a rejected registration is atomic (meaning it either succeeds completely or leaves zero trace behind).
Naive implementations break down in subtle ways across all four parts. In Part 1, looping over ALLOWED_STATUSES.values() checks whether a status exists on any page of the rulebook rather than this device's page—letting gateways enter "INACTIVE" and even accepting unknown types like "printer". In Part 2, checking device_id in self.devices before verifying isinstance(device_id, str) crashes with TypeError on unhashable inputs like ["gw-04"]. And in Part 4, blindly setting "FAULTY" on every failing device puts a failing "sensor" into an illegal status that Part 1 just banned.
Walk through three concrete calls from the examples to see how the pieces fit together:
add_device(Device("gw-04", "gateway", "INACTIVE", 250))looks upALLOWED_STATUSES.get("gateway")({"ACTIVE", "MAINTENANCE", "FAULTY"}), sees"INACTIVE"is missing, returnsFalse, and leavesself.devicesempty.register_device("sen-10", "sensor", "ACTIVE", 50)passes all six ordered checks (INVALID_ID,UNKNOWN_TYPE,STATUS_NOT_ALLOWED,INVALID_TIME,NEGATIVE_TIME,DUPLICATE_ID) and stores"sen-10", socount_active_by_type()includes"sensor"while omitting zero-count categories like"camera".- Suppose
"sen-10"later haslast_maintenance_at = 350andfailure_count = 4. Callingbulk_update_status(now=600, maintenance_interval=200, failure_threshold=2)checks failures first (4 >= 2), sees"FAULTY"is disallowed for"sensor", falls through to maintenance (600 - 350 = 250 >= 200), confirms"MAINTENANCE"is allowed for"sensor", updates"sen-10"to"MAINTENANCE", and counts1real transition.
Complexity
- Time:
is_valid_statusandadd_devicerun in O(1) average time because we do a single dictionary lookup bydevice_typefollowed by a single hash-set membership check forstatus(faster than the buggy version, which looped across every type's set).register_deviceruns in O(1) average time because it performs six constant-time type/value/hash checks and one dictionary insertion intoself.devices.count_active_by_typeruns in O(n + k log k) time fornregistered devices andkdevice types that have at least one"ACTIVE"device: we scan allndevices once in O(n) to tally active counts, then sort thekdistinct active type names (k <= n, typicallyk <= 3).bulk_update_statusruns in O(n) time because we visit each of thenstored devices once and run at most two O(1)is_valid_statuschecks per device.
- Space:
- The registry stores
nDeviceobjects in O(n) space. count_active_by_typeallocates O(k) auxiliary dictionary space for thekactive types, whileis_valid_status,register_device, andbulk_update_statususe O(1) extra space.
- The registry stores
Edge cases
- Unhashable or non-string arguments (
["gw-04"],{"ACTIVE"},None): Checkingisinstance(..., str)before anydictorsetlookup ensuresis_valid_statusreturnsFalseandregister_deviceraisesRegistrationErrorrather than crashing withTypeError: unhashable type. - Boolean timestamps (
registered_at = TrueorFalse): Becauseboolis a subclass ofintin Python (isinstance(True, int)isTrue), we explicitly rejectisinstance(registered_at, bool)before acceptingint. Timestamp0is valid;-1raises"NEGATIVE_TIME". - Empty registry or zero active devices:
count_active_by_type()returns{}cleanly, andbulk_update_status(...)returns0. - Exact threshold boundaries and clock skew in bulk updates:
failure_count == failure_thresholdandnow - last_maintenance_at == maintenance_intervaltrigger updates (>=), whereas1unit below does not. Iflast_maintenance_at > now(clock skew),now - last_maintenance_atis negative and safely treated as not overdue. - Failing sensor that is not yet overdue for maintenance: Because
"sensor"disallows"FAULTY"and maintenance is not overdue ("sen-20"in Example 3),_choose_bulk_targetreturnsNoneand leaves the sensor"ACTIVE"rather than corrupting its state.
Common mistakes
- Patching only one specific type/status pair (
if device_type == "gateway" and status == "INACTIVE": return False): Fixes one symptom while still accepting"sensor"/"FAULTY","camera"/"MAINTENANCE", and unknown types like"printer". - Indexing
ALLOWED_STATUSES[device_type]directly: Raises an unhandledKeyErroron unknown device types like"printer"instead of returningFalseinis_valid_status. - Mutating
self.devicesbefore all checks pass (or inserting first and rolling back on error): Breaks atomicity if an exception interrupts validation halfway through. - Initializing
count_active_by_typewith{t: 0 for t in ALLOWED_STATUSES}: Leaves forbidden0-count entries in the output unless manually stripped, and misses any legacy device whose type was later removed fromALLOWED_STATUSES. - Returning a
collections.defaultdict(int)fromcount_active_by_type: If a caller later accessescounts["camera"]when no cameras are active,defaultdictsilently inserts"camera": 0, violating the zero-omission contract after the fact. - Stopping after the first triggered rule in
bulk_update_statuswhen its target status is disallowed: If a failing, overdue sensor checks"FAULTY", sees"FAULTY"is invalid for sensors, and immediately gives up without checking"MAINTENANCE", an overdue sensor never gets sent to maintenance.
Follow-up questions
- How can you protect
register_deviceagainst race conditions when concurrent threads attempt to claim the samedevice_id? Without synchronization, two threads can suffer a race condition (where correctness depends on unpredictable thread scheduling): both passdevice_id in self.devicesbefore either executesself.devices[device_id] = device, so the second silently overwrites the first—Python's GIL (Global Interpreter Lock, which serializes bytecode instructions) can switch threads right between the check and the write. Add aself._lock = threading.Lock()onDeviceRegistryand wrapregister_device,add_device,bulk_update_status, andcount_active_by_typeinwith self._lock:so check-and-insert executes as one indivisible critical section (or enforce aUNIQUEprimary key constraint if backed by SQL). - Suppose
ALLOWED_STATUSESis reloaded dynamically and drops a status currently assigned to live devices—how should the service handle those records? Never silently mutate or delete live devices during a config reload, because the registry cannot guess the safe physical replacement state. Instead, validate the candidate config againstself.devicesfirst to list any devices holding newly removed statuses, then either reject the reload until an operator migrates those devices or run an explicit, logged migration mapping (such as"MAINTENANCE" -> "INACTIVE"), swapping theALLOWED_STATUSESreference in a single atomic pointer assignment once ready. - How would you design a tamper-evident audit trail that records both manual status edits and automated bulk transitions? Funnel every state transition through a single internal helper
_set_status(device, new_status, actor, reason, timestamp)that appends an immutable event(device_id, old_status, new_status, actor, reason, timestamp)to an append-only audit log (a list or database table where records are only added, never overwritten). Forbulk_update_status, attach a sharedbatch_idand rule reason (such as"bulk:failure_count>=2"), and turnDevice.statusinto a read-only@propertybacked byDevice._statusso external callers cannot mutate statuses behind the audit log's back.
Follow-up questions
- How can you protect `register_device` against race conditions when concurrent threads attempt to claim the same `device_id`?
- Suppose `ALLOWED_STATUSES` is reloaded dynamically and drops a status currently assigned to live devices—how should the service handle those records?
- How would you design a tamper-evident audit trail that records both manual status edits and automated bulk transitions?
Similar questions
- Count Valid Highway Trips
- Real-Time Multi-Server Channel Chat Service
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging