Problem statement

https://leetcode.com/problems/faulty-sensor/

Solution

The idea is to find the biggest common prefix of arrays and then check that the rest parts are shifted by 1: either in one side or in another. If we see that both options can be true, we return -1.

Complexity

Time complexity is O(n), space is O(n) as well.

Code

class Solution:
    def badSensor(self, A1, A2):
        n, found = len(A1), []
        for i in range(n):
            if A1[i] != A2[i]: break
        
        if A1[i:-1] == A2[i+1:]: found += [1]
        if A2[i:-1] == A1[i+1:]: found += [2]
            
        return found[0] if len(found) == 1 else -1