DSA Factory
Free Stacks and queues lessonsStacks and queues · Stage 3 · Queues and deques · Step 4

The longest steady stretch

Find the longest stretch of an array whose biggest and smallest values differ by at most a limit, with two deques tracking the maximum and the minimum of the window. About 20 minutes.

Two deques for one window

You grow a window by moving its right edge. To know how spread out the window is, you need its maximum and its minimum. Last step showed a deque that always gives the maximum. A second deque, mirrored, always gives the minimum.

Each time a value is added, update both deques: the max deque drops smaller values from the back, and the min deque drops bigger values from the back.

Max deque: front is the biggest in the window.
Min deque: front is the smallest in the window.
In code
mx = deque([4, 2])    # 4 is the biggest
mn = deque([1, 3])    # 1 is the smallest
Longest stretch with spread at most 4 in 8, 2, 4, 7, 3, 5.
8
0
2
1
4
2
7
3
3
4
5
5
leftright

The window 8 has spread 0. Length 1.

Move 1 of 6

Shrink while too spread

If the front of the max deque minus the front of the min deque is more than the limit, the window is too spread out. Move the left edge one step to the right. Any deque front that is now left of the window is removed.

Repeat until the window is steady again, then measure its length. The window always contains at least the newest value, so the length is at least 1.

Spread over the limit: move the left edge right.
Drop stale fronts: from both deques.
In code
spread = nums[mx[0]] - nums[mn[0]]
Quick check

The window is too spread out. What do you move?

  1. AThe left edge, to the right
  2. BThe right edge, to the left
  3. CStart again from the right edge
Show the answer

The left edge, to the right. Removing the oldest value is the way to reduce the spread, and a wider window would only be worse.

Your problem

Longest subarray within a limit

You get a list nums and a number limit. Return the length of the longest run of consecutive values in which any two values differ by at most limit.

Example
nums = [10, 1, 2, 4, 7, 2], limit = 5 → 4

1 ≤ length of nums ≤ 100,000 · 1 ≤ nums[i] ≤ 1,000,000,000 · 0 ≤ limit ≤ 1,000,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve