← Questions
Longest subarray with absolute difference within a limit
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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
limitinclusive (difference equal tolimitallowed)? - 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
