š Scenario: You are analyzing daily temperatures recorded over a week. You want to find the highest average temperature over any 3-day period.
šÆ Goal: Build a program that uses the sliding window technique to find the maximum average temperature over any 3 consecutive days.
š What You'll Learn
Create an array called temperatures with exactly these values: [70, 72, 68, 74, 76, 73, 75]
Create a variable called windowSize and set it to 3
Use a for loop with variable i to slide over the array and calculate the sum of each 3-day window
Find and store the maximum sum of any 3-day window in a variable called maxSum
Calculate the maximum average temperature by dividing maxSum by windowSize
Print the maximum average temperature rounded to 2 decimal places
š” Why This Matters
š Real World
Analyzing temperature trends helps in weather forecasting and planning outdoor activities.
š¼ Career
Sliding window technique is widely used in data analysis, signal processing, and performance optimization tasks in software development.
Progress0 / 4 steps
1
Create the temperature data array
Create an array called temperatures with these exact values: [70, 72, 68, 74, 76, 73, 75]
DSA Javascript
Hint
Use const temperatures = [70, 72, 68, 74, 76, 73, 75]; to create the array.
2
Set the sliding window size
Create a variable called windowSize and set it to 3
DSA Javascript
Hint
Use const windowSize = 3; to set the window size.
3
Calculate the maximum sum of any 3-day window
Use a for loop with variable i to slide over temperatures and calculate the sum of each 3-day window. Store the maximum sum in a variable called maxSum. Initialize maxSum with the sum of the first 3 elements.
DSA Javascript
Hint
Start maxSum with the sum of the first 3 temperatures. Then slide the window from index 1 to the end, updating maxSum if you find a bigger sum.
4
Calculate and print the maximum average temperature
Calculate the maximum average temperature by dividing maxSum by windowSize. Then print the result rounded to 2 decimal places using console.log.
DSA Javascript
Hint
Divide maxSum by windowSize and use toFixed(2) to round to 2 decimals before printing.
Practice
(1/5)
1. What is the main purpose of the sliding window technique when working with arrays?
easy
A. To find the maximum element in the entire array
B. To sort the array elements in ascending order
C. To reverse the array elements in place
D. To efficiently process subarrays of fixed size without recomputing everything
Solution
Step 1: Understand the sliding window concept
The sliding window technique moves a fixed-size window over the array to process subarrays efficiently.
Step 2: Compare with other options
Sorting, reversing, or finding max in the entire array are different operations not related to sliding window.
Final Answer:
To efficiently process subarrays of fixed size without recomputing everything -> Option D
Hint: Update sum by subtracting left, adding right element [OK]
Common Mistakes:
Not updating maxSum correctly
Adding instead of subtracting old element
Wrong initial sum calculation
4. Identify the bug in the following sliding window code that finds the maximum sum of subarrays of size k:
function maxSlidingWindowSum(arr, k) {
let maxSum = 0;
let windowSum = 0;
for(let i = 0; i <= k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;
for(let i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
if(windowSum > maxSum) maxSum = windowSum;
}
return maxSum;
}
medium
A. The subtraction in the second loop is incorrect
B. The first loop should run while i < k, not i <= k
C. maxSum should be initialized to Number.MIN_VALUE
D. The function does not handle empty arrays
Solution
Step 1: Check the first loop range
The first loop runs from i = 0 to i <= k, which means it accesses arr[k], an out-of-bound index for window size k.
Step 2: Correct the loop condition
The loop should run while i < k to sum exactly k elements starting from index 0.
Final Answer:
The first loop should run while i < k, not i <= k -> Option B
Quick Check:
Loop range for first window = i < k [OK]
Hint: Loop for first window sums exactly k elements: i < k [OK]
Common Mistakes:
Using <= k causes out-of-bounds error
Ignoring array length checks
Incorrect initialization of maxSum
5. Given an array of integers and a number k, how would you find the length of the longest subarray with sum less than or equal to k using the sliding window technique?
hard
A. Calculate prefix sums and find max subarray sum using Kadane's algorithm
B. Sort the array and use binary search to find subarrays with sum ⤠k
C. Expand the window by moving right pointer and shrink from left when sum exceeds k, track max length
D. Use nested loops to check all subarrays and pick the longest with sum ⤠k
Solution
Step 1: Use two pointers to create a sliding window
Start with both pointers at the beginning, expand right pointer to add elements to sum.
Step 2: Shrink window from left when sum exceeds k
If sum > k, move left pointer forward to reduce sum until sum ⤠k again, tracking max window length.
Step 3: Track the maximum length of valid windows
Keep updating max length whenever sum ⤠k during expansion and shrinking.
Final Answer:
Expand the window by moving right pointer and shrink from left when sum exceeds k, track max length -> Option C
Quick Check:
Sliding window with two pointers and sum check = Expand the window by moving right pointer and shrink from left when sum exceeds k, track max length [OK]
Hint: Move right to expand, left to shrink when sum > k [OK]
Common Mistakes:
Using sorting or binary search which doesn't apply here
Using nested loops causing O(n²) time
Confusing Kadane's algorithm with sum limit problem
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.