Problem Description
Two sensors record a sequence of data points. However, one of the sensors may be faulty: it "drops" exactly one data point from the correct sequence, shifting all later values one position to the left and replacing the final element with a random value (which is guaranteed not to be equal to the dropped value). Given two arrays, sensor1 and sensor2, determine which sensor is defective (i.e. its output can be produced by dropping one data point from the correct sensor’s output). If there is no defect or it is impossible to decide with certainty, return -1.
Key Insights
- One sensor’s data is correct while the other, if faulty, will equal the correct array with exactly one element missing (and with its last element replaced by an arbitrary value that does not equal the dropped value).
- For the faulty sensor, the first part of its output will match the correct sensor except that at the drop index, every subsequent element is “shifted left” compared to the correct readings.
- We can simulate this by iterating over the arrays using two pointers, allowing exactly one “skip” in the correct (supposed) sensor’s array.
- We must consider both possibilities – sensor1 could be faulty with sensor2 correct, or sensor2 could be faulty with sensor1 correct. If both cases yield a valid explanation, the answer is ambiguous and we return -1.
Space and Time Complexity
Time Complexity: O(n), where n is the number of data points (at most 100).
Space Complexity: O(1)
Solution
We solve the problem by writing a helper routine that checks if an array F (faulty candidate) can be derived from array P (presumed correct) by having exactly one dropped element. The faulty sensor must match P exactly for the first several points and then, at one index, “skip” one element from P so that subsequent elements align, with the last element of F being arbitrary. We perform a two–pointer scan, allowing exactly one skip. We then test both possibilities:
- Check if sensor1 can be explained as faulty when sensor2 is assumed correct.
- Check if sensor2 can be explained as faulty when sensor1 is assumed correct. If exactly one of these tests passes, return the corresponding sensor number; otherwise, return -1.
Key data structures and techniques:
- Two pointers (one iterating over the presumed correct array and one for the candidate faulty sensor).
- A boolean flag to allow exactly one discrepancy (i.e. one skip in the correct array).