← Questions

Longest subarray with absolute difference within a limit

0
UberCodingLast asked May 2026

A coding interview question asked in Uber's coding round, last asked May 2026. It tests sliding window, monotonic deque and arrays.

Given an integer array and a non-negative limit, return the length of the longest contiguous subarray in which any two elements differ by at most limit. Equivalently, the subarray's maximum minus its minimum is at most limit.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • longest_subarray(nums: list[int], limit: int) -> int — the length of the longest qualifying subarray. Any single element qualifies, so the answer is at least 1 for a non-empty array.

Example

longest_subarray([8, 2, 4, 7], 4)                ->  2    # [2, 4] or [4, 7]
longest_subarray([10, 1, 2, 4, 7, 2], 5)         ->  4    # [2, 4, 7, 2]
longest_subarray([4, 2, 2, 2, 4, 4, 2, 2], 0)    ->  3    # [2, 2, 2]

Constraints

  • 1 <= len(nums) <= 10^5, 1 <= nums[i] <= 10^9, 0 <= limit <= 10^9.

Clarifying questions

  • Is limit inclusive (difference equal to limit allowed)?
  • Should I return the length or the subarray itself?
  • Can the array be empty?

What a strong answer covers

  • The brute force over all subarrays, O(n²) or worse, as a baseline.
  • A sliding window: extend the right end, and move the left end while max − min exceeds limit.
  • Two monotonic deques, one decreasing for the maximum and one increasing for the minimum, so each element is pushed and popped once: O(n) time.
  • A sorted multiset or two heaps with lazy deletion as an O(n log n) alternative.
  • Tests: limit = 0, all equal values, strictly increasing input.

Follow-ups

  • Return the starting index of the longest window as well.
  • Elements arrive as a stream. Report the longest qualifying window seen so far after each one.
  • Count all subarrays whose max − min is at most limit.

Where it's asked

  • Uber · Coding · Last asked May 202660 min · Two rounds; one is often object-oriented design (a parking lot, a meeting scheduler, an expression evaluator) · No AI, except a newer AI-assisted debugging round in some senior loops

What it tests

sliding window · monotonic deque · arrays

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding