KatInterview

Find Longest Subarray with Bounded Absolute Difference

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

Last updated

Tests the ability to use two pointers alongside auxiliary tracking structures to find the longest contiguous subarray where max−min does not exceed a given threshold.

Longest Subarray with Bounded Spread

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

Find the length of the longest contiguous subarray such that the difference between the maximum and minimum values in that subarray is at most limit.

A subarray is a contiguous, non-empty portion of the array.

Constraints

  • 1 <= len(nums) <= 2000
  • -10^6 <= nums[i] <= 10^6
  • 0 <= limit <= 2 * 10^6
  • If multiple subarrays tie for the longest length, return the length (any such subarray gives the same answer).

Examples

Example 1

Input: longest_bounded_spread([4, 2, 2, 5, 1, 6, 3], 2)

Output: 3

Example 2

Input: longest_bounded_spread([1, 5, 6, 7, 8, 10, 6, 5, 6], 4)

Output: 5

Example 3

Input: longest_bounded_spread([10], 0)

Output: 1

Hints

Hint 1

Try maintaining a sliding window [left, right] and ask: when does expanding right make the window invalid?

Hint 2

You need the current max and min of the window efficiently. Consider what data structures let you add an element from the right and remove an element from the left while tracking max/min.

Hint 3

Two monotonic deques — one for max, one for min — let you maintain the window's extremes in amortized O(1) per move, giving an overall O(n) solution.