VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-subarray-in-which-absolute-difference-between-any-two-element-is-not-greater-than-x/

⇱ Longest subarray with absolute difference between any pair at most X - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest subarray with absolute difference between any pair at most X

Last Updated : 22 Sep, 2025

Given an integer array arr[] and an integer x, Find the longest sub-array where the absolute difference between any two elements is not greater than x

Examples:

Input: arr[] = [8, 4, 5, 6, 7], x = 3
Output: [4, 5, 6, 7] 
Explanation: The longest valid subarray is [4, 5, 6, 7] because max = 7, min = 4 β†’ difference = 3 which is less than equal to x.

Input: arr[] = [1, 10, 12, 13, 14], x = 2
Output: [12, 13, 14] 
Explanation: The longest valid subarray is [12, 13, 14] because max = 14, min = 12 β†’ difference = 2 which is less than equal to x.

[Naive Approach] Checking all subarrays - O(n3) Time and O(1) Space

The idea is to consider all subarrays one by one, find the maximum and minimum element of that sub-array and check if their difference is not greater than x. Among all such sub-arrays print the longest sub-array.


Output
4 5 6 7 

[Better Approach] Using Sliding Window and Sorted Map - O(n * log n) Time and O(n) Space

We use a sliding window with an ordered map to maintain the minimum and maximum values in the current subarray. The window expands until the absolute difference exceeds x; if it does, we shrink the window from the left until the condition is satisfied again.

Working:

  • Maintain two pointers start and end for the window.
  • Insert elements into the map to track min and max.
  • If (max - min) <= x, update the best subarray length.
  • If (max - min) > x, move start forward and remove elements until valid.
  • Finally, return the longest valid subarray found.

In C# and JavaScript, a custom structure is needed for min/max since they don’t have a built-in ordered map.


Output
4 5 6 7 

[Expected Approach] Using Dequeues - O(n) Time and O(n) Space

We will be using two deques to maintain the minimum and maximum of the current window in O(1). Expand the window while the difference ≀ x, and shrink it when the difference > x to find the longest valid subarray.

Working:

  1. Keep two deques:
    -> minDeque β†’ increasing order (front = minimum).
    -> maxDeque β†’ decreasing order (front = maximum).
  2. Traverse array with end pointer:
    -> Insert element in both deques while maintaining order.
  3. If (maxDeque.front() - minDeque.front()) > x:
    -> Move start pointer forward.
    -> Remove elements from deques if they go out of the window.
  4. Track the maximum window size where difference ≀ x.

Output
4 5 6 7 
Comment
Article Tags: