KatInterview

Longest Subarray with Bounded Pairwise Spread

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingarraystwo pointerssliding window

Last updated

Tests ability to use the two-pointer (sliding window) technique to find the longest contiguous subarray where the difference between the max and min elements stays within a given limit.

Longest Subarray with Bounded Pairwise Spread

You are given a list of integers nums and a non-negative integer limit.

A subarray is valid if the difference between its maximum element and its minimum element is at most limit:

max(subarray) - min(subarray) <= limit

Return the length of the longest valid contiguous subarray. If nums is empty, return 0.

Constraints

  • 0 <= len(nums) <= 2000
  • -10^6 <= nums[i] <= 10^6
  • 0 <= limit <= 2 * 10^6
  • All integers in nums may not be distinct.
  • If there are multiple subarrays of the same maximum length, any of them qualifies — only the length is returned.

Examples

Example 1

Input: longest_bounded_spread_subarray([4, 8, 5, 1, 7, 9], 3)

Output: 2

Example 2

Input: longest_bounded_spread_subarray([1, 1, 1, 1], 0)

Output: 4

Example 3

Input: longest_bounded_spread_subarray([], 5)

Output: 0

Hints

Hint 1

Try maintaining a sliding window [left, right] and track the current max and min as you expand right. When the spread exceeds limit, advance left.

Hint 2

Naively recomputing max and min on each window expansion is O(n²). Think about data structures that let you track a running max and running min efficiently as the window shrinks from the left — but even a simple O(n²) inner scan is acceptable for n ≤ 2000.

Hint 3

When you move `left` forward, you only need to keep moving it until max - min <= limit again. Recompute the window's max and min from scratch after each shift if needed for simplicity.