888910. Longest Bounded-Difference Subarray

Medium

Here is the detailed Markdown blog post for the Longest Bounded-Difference Subarray problem:

Longest Bounded-Difference Subarray

Summary

Given an array of integers, find the longest subarray such that the absolute difference between any two elements in the subarray does not exceed a given bound. The goal is to maximize the length of this subarray.

This problem involves arrays and bounded differences, which are key concepts covered by the tags "Arrays" and "Heap".

Detailed Explanation

To solve this problem, we can use a sliding window approach with two pointers, left and right, initialized at the start of the array. We also maintain a variable max_length to keep track of the maximum length of the subarray seen so far.

We iterate through the array, expanding the window to the right as long as the absolute difference between the elements at the left and right pointers does not exceed the given bound. When we find that the difference exceeds the bound, we slide the window to the right by moving the left pointer one step to the right.

At each step, we update max_length if the current length of the subarray is greater than what we have seen so far.

Here's a step-by-step breakdown:

  1. Initialize left, right, and max_length.
  2. Iterate through the array:
    • While the absolute difference between elements at left and right does not exceed the bound, increment right and update max_length if necessary.
    • When the difference exceeds the bound, increment left and reset the window.
  3. Return max_length.

Time complexity: O(n), where n is the length of the input array.

Space complexity: O(1), as we only use a few extra variables to store the pointers and maximum length.

Optimized Solutions

Java

View on GeeksforGeeks
public int longestBoundedDifferenceSubarray(int[] arr, int bound) {
    int left = 0;
    int right = 0;
    int max_length = 0;

    while (right < arr.length) {
        while (Math.abs(arr[right] - arr[left]) > bound) {
            left++;
        }
        max_length = Math.max(max_length, right - left + 1);
        right++;
    }

    return max_length;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.