File: faulty-sensor/solution.py

Date: 2026-06-06

Time: 16:31

faulty-sensor/solution.py

Purpose

This file solves LeetCode 1826 — Faulty Sensor. Given two sensor arrays that should be identical but one may have dropped a single reading (causing all subsequent values to shift left by one, with an arbitrary value appended at the end), determine which sensor is defective — or report that it's indeterminate.

Key Components

Solution.badSensor(sensor1, sensor2) -> int

The single method. Contract:

Flow

The algorithm has three stages:

1. Find first divergence (lines 14–16): Walk both arrays in lockstep until a mismatch is found. This prefix of agreement tells us nothing — the defect must be at or after position i.

2. Early exit (lines 18–19): If i >= n - 1, the arrays are either identical or differ only at the very last element. In both cases, you can't distinguish which sensor dropped a value — either hypothesis produces a valid shifted suffix — so return -1.

3. Test both hypotheses (lines 21–27):

If both or neither hypothesis holds, return -1. Otherwise return which sensor is faulty.

Patterns

Dependencies

Invariants

Error Handling

None. The code trusts its inputs per LeetCode conventions — no bounds checking, no type validation. Invalid inputs (different-length arrays, empty arrays) would produce undefined behavior, not exceptions.

Topics to Explore

Beliefs