easyArraysPattern: Two Pointers

Longest Common Amplitude Segment Solution

Problem Statement

Given two arrays of integers, find the length of the longest contiguous segment where the absolute difference between corresponding elements in both arrays is the same.

Examples

Example 1:
Input:[1, 3, 5, 7, 9] [2, 4, 6, 8, 10]
Output:5
Explanation: The absolute difference between corresponding elements in the longest contiguous segment [1, 3, 5, 7, 9] and [2, 4, 6, 8, 10] is 1 for all elements.
Example 2:
Input:[10, 20, 30, 40, 50] [15, 25, 35, 45, 55]
Output:5
Explanation: The absolute difference between corresponding elements in the longest contiguous segment [10, 20, 30, 40, 50] and [15, 25, 35, 45, 55] is 5 for all elements.
Example 3:
Input:[] []
Output:0
Explanation: The input arrays are empty.

Constraints

  • 1 <= arr1.length, arr2.length <= 1000
  • -1000 <= arr1[i], arr2[i] <= 1000
  • arr1 and arr2 may not be the same length
Time: O(n^2) Space: O(1)
The optimized approach is to use a single loop to compare the absolute difference between corresponding elements in both arrays, resulting in a time complexity of O(n).

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

def longest_common_amplitude_segment(arr1, arr2): if not arr1 or not arr2: return 0 max_len = 0 for i in range(min(len(arr1), len(arr2))): diff = abs(arr1[i] - arr2[i]) length = 1 for j in range(i + 1, min(len(arr1), len(arr2))): if abs(arr1[j] - arr2[j]) == diff: length += 1 else: break max_len = max(max_len, length) return max_len