All problems
Lead-Lag Best Lag
Problem
Find the lag that best aligns two equal-length series by absolute Pearson correlation. For lag k >= 0 compare x[0..n-k-1] with y[k..n-1]; for k < 0 compare x[-k..n-1] with y[0..n+k-1]. Search every lag from -max_lag to max_lag.
Return the lag with the largest absolute correlation; ties prefer the lag closest to zero, and at equal distance the negative one. Return None when no lag has at least two paired points.
Hint
Iterate candidate lags in order 0, -1, 1, -2, 2 to settle ties deterministically.
Test cases
case 1
in: [[1,4,9,16,25,36],[0,1,4,9,16,25],2]
expected: 1
case 2
in: [[1,2,3,4,5,6],[20,21,22,23,24,25],2]
expected: 0
case 3
in: [[1,4,9,16,25,36],[4,9,16,25,36,49],2]
expected: -1
case 4
in: [[1,2,3],[3,2,1],2]
expected: 0
case 5
in: [[0,1,3,2,5,4],[1,3,2,5,4,7],2]
expected: -1
Starter codePython
def best_lag(x, y, max_lag):
# Your code here
pass5 test cases · run your code against them in the editor