1. Brute Force

class Solution:
    def badSensor(self, sensor1: List[int], sensor2: List[int]) -> int:
        n = len(sensor1)

        def isFaulty(bad, good):
            for d in range(n):
                ok = True
                for j in range(n - 1):
                    k = j if j < d else j + 1
                    if bad[j] != good[k]:
                        ok = False
                        break
                if ok:
                    return True
            return False

        one = isFaulty(sensor1, sensor2)
        two = isFaulty(sensor2, sensor1)
        if one == two:
            return -1
        return 1 if one else 2

Time & Space Complexity

  • Time complexity: O(n2)O(n ^ 2)
  • Space complexity: O(1)O(1)

Where nn is the length of the arrays sensor1sensor1 and sensor2sensor2.


2. Two Pointers

class Solution:
    def badSensor(self, sensor1: List[int], sensor2: List[int]) -> int:
        n = len(sensor1)
        i = 0
        while i < n and sensor1[i] == sensor2[i]:
            i += 1

        one = two = True
        for j in range(i, n - 1):
            if sensor1[j] != sensor2[j + 1]:
                one = False
            if sensor2[j] != sensor1[j + 1]:
                two = False

        if one == two:
            return -1
        return 1 if one else 2

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1)

Where nn is the length of the arrays sensor1sensor1 and sensor2sensor2.


3. Two Pointers (One Pass)

class Solution:
    def badSensor(self, sensor1: List[int], sensor2: List[int]) -> int:
        n = len(sensor1)
        i = 0
        while i < n and sensor1[i] == sensor2[i]:
            i += 1
        while i + 1 < n and sensor1[i] == sensor2[i + 1] and sensor1[i + 1] == sensor2[i]:
            i += 1

        if i >= n - 1:
            return -1
        return 1 if sensor1[i] == sensor2[i + 1] else 2

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1)

Where nn is the length of the arrays sensor1sensor1 and sensor2sensor2.