Faulty Sensor — LeetCode 1826 Python Solution

EasyLeetCode PremiumArrayTwo Pointers
Problem
#1826
Reading time
3 min

The problem

An experiment is being conducted in a lab. To ensure accuracy, there are two sensors collecting data simultaneously.

Example

Input
sensor1 = [2,3,4,5], sensor2 = [2,1,3,4]
Output
1
Explanation
Sensor 2 has the correct values.

Python solution

Python
class Solution:
    def badSensor(self, sensor1: List[int], sensor2: List[int]) -> int:
        i, n = 0, len(sensor1)
        while i < n - 1:
            if sensor1[i] != sensor2[i]:
                break
            i += 1
        while i < n - 1:
            if sensor1[i + 1] != sensor2[i]:
                return 1
            if sensor1[i] != sensor2[i + 1]:
                return 2
            i += 1
        return -1

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1826. Faulty Sensor is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1826. Faulty Sensor?
LeetCode 1826. Faulty Sensor is rated Easy on LeetCode.
What is the time complexity of LeetCode 1826. Faulty Sensor?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 1826. Faulty Sensor?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1826. Faulty Sensor cover?
LeetCode 1826. Faulty Sensor is tagged Array and Two Pointers on LeetCode.
Is LeetCode 1826. Faulty Sensor a premium problem?
Yes. LeetCode 1826. Faulty Sensor is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview