BackeasySliding WindowZomatoTCS

Minimized Range Extent Solution

Problem Statement

You are provided with an array of integers representing a sequence of measurements. Your task is to determine the minimum possible range extent by selecting a contiguous subarray of a fixed length k. The range extent of a subarray is defined as the difference between its maximum and minimum elements. Using a sliding window approach, efficiently compute the smallest range extent across all valid windows of size k.

Input: An array of integers nums and an integer k representing the window size. Output: Return the minimum range extent (max - min) among all contiguous subarrays of length k. If k is greater than the length of the array, return -1.

Example 1
Input
nums = [4, 2, 1, 8, 7], k = 3
Output
2

Explanation: Window 1: [4, 2, 1] -> max=4, min=1, range=3. Window 2: [2, 1, 8] -> max=8, min=1, range=7. Window 3: [1, 8, 7] -> max=8, min=1, range=7. The minimum range is 2 (from window [4,2,1] is 3, wait, let's recheck: [4,2,1] range=3, [2,1,8] range=7, [1,8,7] range=7. Actually, let's pick a better example. Let's use nums = [1, 5, 3, 2, 4], k=3. Window 1: [1,5,3] range=4. Window 2: [5,3,2] range=3. Window 3: [3,2,4] range=2. Min is 2. Let's use this one. Revised Example 1: nums = [1, 5, 3, 2, 4], k = 3. Output: 2. Explanation: Window [1,5,3] has max 5, min 1, range 4. Window [5,3,2] has max 5, min 2, range 3. Window [3,2,4] has max 4, min 2, range 2. The minimum range is 2.

Example 2
Input
nums = [10, 1, 2, 3, 4], k = 4
Output
9

Explanation: Window 1: [10, 1, 2, 3] -> max=10, min=1, range=9. Window 2: [1, 2, 3, 4] -> max=4, min=1, range=3. The minimum range is 3. Wait, 9 is not the min. Let's correct. Output should be 3. Explanation: Window [10,1,2,3] range 9. Window [1,2,3,4] range 3. Min is 3.

Example 3
Input
nums = [7, 7, 7, 7], k = 2
Output
0

Explanation: All windows consist of identical values. Window [7,7] range 0. Window [7,7] range 0. Window [7,7] range 0. The minimum range is 0.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= k <= nums.length
  • -10^9 <= nums[i] <= 10^9
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Minimized Range Extent — Problem Statement & Solution Guide

Sliding WindowEasyFixed Length Window
TimeO(n)
|
SpaceO(k)

Problem Description

You are provided with an array of integers representing a sequence of measurements. Your task is to determine the minimum possible range extent by selecting a contiguous subarray of a fixed length k. The range extent of a subarray is defined as the difference between its maximum and minimum elements. Using a sliding window approach, efficiently compute the smallest range extent across all valid windows of size k.

Input: An array of integers nums and an integer k representing the window size.

Output: Return the minimum range extent (max - min) among all contiguous subarrays of length k. If k is greater than the length of the array, return -1.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Minimized Range Extent"

easy

WHY DOES IT MATTER?

Monotonic queue sliding‑window patterns appear in many real‑time analytics, stock‑price monitoring, and sensor‑data processing tasks where you need instant extremum information over a moving horizon.

OPTIMIZATION CHALLENGE

The key insight is that an element that is smaller than a newer element can never become the minimum for any future window that includes the newer element, so it can be safely discarded from the deque, guaranteeing each element is processed only once.

REAL-WORLD CONNECTION

Think of a conveyor belt with packages of varying weight; you want to know the lightest and heaviest package in the last k positions at any moment without stopping the belt to recount each time.

When coding, keep the deque indices (not values) to easily verify whether the front element is still inside the current window; this avoids subtle bugs when duplicate values appear.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
đź’ľ Space:O(k)

Core Theory — Why This Approach?

The problem asks for the smallest possible range (max‑min) among all contiguous subarrays of length k. A naive solution would recompute the maximum and minimum for each window, leading to O(n·k) time, which quickly becomes infeasible for large n (up to 10^5 or more). The optimal paradigm leverages a sliding window combined with two double‑ended queues (deques) that maintain candidates for the current window's maximum and minimum in monotonic order. As the window slides one position to the right, elements that fall out of the window are removed from the front of each deque, and the new element is inserted while discarding any values that can never become the max or min for future windows. This yields O(n) overall time because each array element is pushed and popped at most once.

The underlying theory rests on the concept of monotonic queues: a data structure that supports O(1) retrieval of the extremum (max or min) for a sliding window while preserving amortized O(1) updates. By keeping the deque in decreasing order for the maximum queue and increasing order for the minimum queue, the front always holds the true extremum for the current window. This eliminates the need for repeated scans, turning a potentially quadratic algorithm into a linear one, which is essential for meeting typical competitive‑programming and interview constraints.

Interview Questions on This Problem

Q1How would you modify the solution if the window size k is not fixed but can vary for each query?

Preprocess the array using a segment tree or sparse table to answer range max/min queries in O(log n) or O(1) respectively, then each query for a specific k becomes O(1) after O(n log n) preprocessing. Alternatively, maintain a sliding window for each distinct k if the number of queries is small.

Q2Can you solve the problem using a balanced BST (e.g., multiset) instead of deques? What are the trade‑offs?

Yes, insert each new element into the BST and erase the element that slides out; the current min and max are the first and last elements. This yields O(n log k) time and O(k) space, which is slower than the O(n) deque solution but simpler to code when language libraries provide ordered containers.

Q3Explain why a simple sliding‑window sum technique cannot be directly applied to compute max‑min range.

Sum can be updated incrementally because addition/subtraction is associative and invertible. Max and min are not invertible; removing an element may change the extremum in a non‑local way, requiring a data structure that can efficiently discard outdated candidates, which deques provide.

Examples

Example 1

Input

nums = [4, 2, 1, 8, 7], k = 3

Output

2

Explanation: Window 1: [4, 2, 1] -> max=4, min=1, range=3. Window 2: [2, 1, 8] -> max=8, min=1, range=7. Window 3: [1, 8, 7] -> max=8, min=1, range=7. The minimum range is 2 (from window [4,2,1] is 3, wait, let's recheck: [4,2,1] range=3, [2,1,8] range=7, [1,8,7] range=7. Actually, let's pick a better example. Let's use nums = [1, 5, 3, 2, 4], k=3. Window 1: [1,5,3] range=4. Window 2: [5,3,2] range=3. Window 3: [3,2,4] range=2. Min is 2. Let's use this one. Revised Example 1: nums = [1, 5, 3, 2, 4], k = 3. Output: 2. Explanation: Window [1,5,3] has max 5, min 1, range 4. Window [5,3,2] has max 5, min 2, range 3. Window [3,2,4] has max 4, min 2, range 2. The minimum range is 2.

Example 2

Input

nums = [10, 1, 2, 3, 4], k = 4

Output

9

Explanation: Window 1: [10, 1, 2, 3] -> max=10, min=1, range=9. Window 2: [1, 2, 3, 4] -> max=4, min=1, range=3. The minimum range is 3. Wait, 9 is not the min. Let's correct. Output should be 3. Explanation: Window [10,1,2,3] range 9. Window [1,2,3,4] range 3. Min is 3.

Example 3

Input

nums = [7, 7, 7, 7], k = 2

Output

0

Explanation: All windows consist of identical values. Window [7,7] range 0. Window [7,7] range 0. Window [7,7] range 0. The minimum range is 0.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= k <= nums.length
  • -10^9 <= nums[i] <= 10^9

Optimal Approach & Strategy

Use two monotonic deques to keep track of the current window's max and min in amortized O(1) per slide, yielding an overall O(n) solution.

Brute Force Approach

Iterate over every possible subarray of length k, compute its max and min by scanning k elements, and track the smallest difference.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
   let min = nums[0];
   let max = nums[0];
   let result = nums.length;
   for (let i = 1; i < nums.length; i++) {
       if (nums[i] - nums[i - 1] > 0) {
           result = Math.min(result, max - min);
           min = nums[i];
       } else if (nums[i] - nums[i - 1] < 0) {
           result = Math.min(result, max - min);
           max = nums[i];
       }
   }
   return result;
}

Asked in Top Tech Interviews

ZomatoTCS

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.