Bird
Raised Fist0
DSA Typescriptprogramming~10 mins

Sliding Window on Arrays in DSA Typescript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Sliding Window on Arrays
Start
↓
Initialize window pointers: start=0, end=0
↓
Expand window by moving end pointer
↓
Check window size or condition
↓
Process window
↓
Slide window by moving start pointer
↓
Repeat until end reaches array end
↓
End
Start with two pointers defining a window on the array. Expand the window by moving the end pointer, check conditions, process the window, then slide the window by moving the start pointer. Repeat until the window covers the array.
Execution Sample
DSA Typescript
const arr = [2, 1, 5, 2, 3, 2];
const k = 3;
let maxSum = 0;
let windowSum = 0;
let windowStart = 0;
for (let windowEnd = 0; windowEnd < arr.length; windowEnd++) {
  windowSum += arr[windowEnd];
  if (windowEnd >= k - 1) {
    maxSum = Math.max(maxSum, windowSum);
    windowSum -= arr[windowStart];
    windowStart++;
  }
}
Find the maximum sum of any contiguous subarray of size k using a sliding window.
Execution Table
StepOperationWindow StartWindow EndWindow ElementsWindow SumMax SumPointer ChangesVisual State
1Add arr[0]=200[2]20windowEnd=02 -> null
2Add arr[1]=101[2,1]30windowEnd=12 -> 1 -> null
3Add arr[2]=502[2,1,5]88windowEnd=22 -> 1 -> 5 -> null
4Slide window: remove arr[0]=212[1,5]68windowStart=11 -> 5 -> null
5Add arr[3]=213[1,5,2]88windowEnd=31 -> 5 -> 2 -> null
6Slide window: remove arr[1]=123[5,2]78windowStart=25 -> 2 -> null
7Add arr[4]=324[5,2,3]1010windowEnd=45 -> 2 -> 3 -> null
8Slide window: remove arr[2]=534[2,3]510windowStart=32 -> 3 -> null
9Add arr[5]=235[2,3,2]710windowEnd=52 -> 3 -> 2 -> null
10Slide window: remove arr[3]=245[3,2]510windowStart=43 -> 2 -> null
11End: windowEnd=6 (array length)45[3,2]510No change3 -> 2 -> null
💡 windowEnd reached array length 6, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6After 7After 8After 9After 10Final
windowStart000112233444
windowEnd012233445566
windowSum0238687105755
maxSum00088881010101010
Key Moments - 3 Insights
Why do we start sliding the window only after windowEnd reaches k-1?
Because before windowEnd reaches k-1, the window size is smaller than k, so we cannot process a full window yet. See execution_table rows 1-3 where windowEnd < 2, windowSum accumulates but maxSum is not updated.
Why do we subtract arr[windowStart] when sliding the window?
Subtracting arr[windowStart] removes the element leaving the window to keep the windowSum accurate for the new window. See execution_table row 4 where arr[0]=2 is removed from windowSum.
How do windowStart and windowEnd pointers move relative to each other?
windowEnd always moves forward by one each iteration, expanding the window. windowStart moves forward only after the window reaches size k, sliding the window forward. See variable_tracker for pointer values.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 7, what is the maxSum value?
A8
B7
C10
D6
💡 Hint
Check the 'Max Sum' column at step 7 in execution_table
At which step does the window first slide forward by removing an element?
AStep 3
BStep 4
CStep 5
DStep 2
💡 Hint
Look for the first 'Slide window' operation in execution_table
If k was changed to 2, how would the window size check in execution_table change?
ASliding starts after windowEnd >= 1
BSliding starts after windowEnd >= 2
CSliding starts after windowEnd >= 0
DSliding never starts
💡 Hint
Sliding starts when windowEnd >= k-1, so with k=2, it starts at windowEnd=1
Concept Snapshot
Sliding Window on Arrays:
- Use two pointers (start, end) to define a window
- Expand window by moving end pointer
- When window size reaches k, process window
- Slide window by moving start pointer and adjusting sums
- Repeat until end reaches array end
- Efficient for fixed-size or condition-based subarray problems
Full Transcript
Sliding window technique uses two pointers to create a moving window over an array. We start both pointers at zero. We expand the window by moving the end pointer and adding elements to the window sum. Once the window size reaches the target size k, we process the window (e.g., update max sum). Then we slide the window forward by moving the start pointer and subtracting the element leaving the window from the sum. This repeats until the end pointer reaches the end of the array. This method avoids recomputing sums from scratch and is efficient for fixed-size subarray problems.

Practice

(1/5)
1. What is the main purpose of the sliding window technique on arrays?
easy
A. To find the maximum element in the entire array
B. To sort the array in ascending order
C. To reverse the elements of the array
D. To efficiently process subarrays of fixed size without repeated work

Solution

  1. Step 1: Understand the sliding window concept

    The sliding window technique moves a fixed-size window over the array to process subarrays efficiently.
  2. Step 2: Identify the purpose

    It avoids recalculating values for overlapping parts of subarrays, improving performance.
  3. Final Answer:

    To efficiently process subarrays of fixed size without repeated work -> Option D
  4. Quick Check:

    Sliding window = efficient fixed-size subarray processing [OK]
Hint: Think of a moving window over array parts for efficiency [OK]
Common Mistakes:
  • Confusing sliding window with sorting
  • Thinking it reverses the array
  • Assuming it finds max of whole array
2. Which of the following is the correct TypeScript syntax to start a sliding window loop for an array arr with window size k?
easy
A. for (let i = 0; i < arr.length; i += k)
B. for (let i = 0; i < arr.length + k; i++)
C. for (let i = 0; i <= arr.length - k; i++)
D. for (let i = 1; i <= arr.length - k; i++)

Solution

  1. Step 1: Determine loop range for sliding window

    The window of size k must fit inside the array, so the last start index is arr.length - k.
  2. Step 2: Check loop syntax correctness

    Loop from i = 0 up to and including arr.length - k ensures all windows are covered.
  3. Final Answer:

    for (let i = 0; i <= arr.length - k; i++) -> Option C
  4. Quick Check:

    Loop runs from 0 to arr.length - k inclusive [OK]
Hint: Loop until index allows full window inside array [OK]
Common Mistakes:
  • Using < instead of <= causing last window to miss
  • Starting loop at 1 instead of 0
  • Incrementing by k skipping windows
3. What is the output of this TypeScript code?
const arr = [1, 3, 2, 6, -1, 4, 1, 8, 2];
const k = 5;
const result: number[] = [];
let windowSum = 0;

for (let i = 0; i < k; i++) {
  windowSum += arr[i];
}
result.push(windowSum);

for (let i = k; i < arr.length; i++) {
  windowSum += arr[i] - arr[i - k];
  result.push(windowSum);
}

console.log(result);
medium
A. [11, 14, 12, 18, 14]
B. [11, 10, 12, 15, 13]
C. [11, 14, 17, 20, 23]
D. [11, 13, 15, 17, 19]

Solution

  1. Step 1: Calculate initial window sum for first 5 elements

    1 + 3 + 2 + 6 + (-1) = 11. result = [11]
  2. Step 2: Slide window and update sums

    i=5: 11 - 1 + 4 = 14
    i=6: 14 - 3 + 1 = 12
    i=7: 12 - 2 + 8 = 18
    i=8: 18 - 6 + 2 = 14
    result = [11, 14, 12, 18, 14]
  3. Final Answer:

    [11, 14, 12, 18, 14] -> Option A
  4. Quick Check:

    windowSum += arr[i] - arr[i - k] each slide [OK]
Hint: Add new element, subtract old element for each slide [OK]
Common Mistakes:
  • Not subtracting the element leaving the window
  • Incorrect initial sum calculation
  • Off-by-one errors in loop indices
4. Identify the error in this sliding window code snippet and choose the fix:
const arr = [2, 1, 5, 1, 3, 2];
const k = 3;
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 = windowSum + arr[i] - arr[i + k];
  if (windowSum > maxSum) {
    maxSum = windowSum;
  }
}
console.log(maxSum);
medium
A. Initialize maxSum to Number.MIN_VALUE
B. Change arr[i + k] to arr[i - k] in the second loop
C. Change first loop to run from i = 1 to k
D. Add a check if i + k < arr.length before subtraction

Solution

  1. Step 1: Analyze the sliding window update

    The window slides by removing the element leaving the window and adding the new element entering it. The element leaving is at index i - k, not i + k.
  2. Step 2: Correct the subtraction index

    Change arr[i + k] to arr[i - k] to correctly remove the leftmost element of the previous window.
  3. Final Answer:

    Change arr[i + k] to arr[i - k] in the second loop -> Option B
  4. Quick Check:

    Subtract element leaving window at i-k [OK]
Hint: Subtract element at i-k, not i+k, when sliding window [OK]
Common Mistakes:
  • Using wrong index for element leaving window
  • Not initializing maxSum correctly
  • Loop range errors
5. Given an array of integers, write a sliding window algorithm to find the maximum sum of any subarray of size k. Which approach below correctly implements this in TypeScript?
hard
A. Initialize sum of first k elements, then slide window adding new element and subtracting old, updating max sum each time
B. Sort the array and sum the first k elements
C. Use nested loops to sum every subarray of size k and track max sum
D. Add all elements and divide by k to get average, then multiply by k for max sum

Solution

  1. Step 1: Understand the sliding window max sum approach

    Calculate sum of first k elements as initial window sum.
  2. Step 2: Slide window across array

    For each new element, add it and subtract the element leaving the window, update max sum if current sum is higher.
  3. Step 3: Avoid inefficient methods

    Sorting or nested loops are less efficient; averaging does not find max sum.
  4. Final Answer:

    Initialize sum of first k elements, then slide window adding new element and subtracting old, updating max sum each time -> Option A
  5. Quick Check:

    Sliding window updates sum and tracks max [OK]
Hint: Slide window, update sum and max in one pass [OK]
Common Mistakes:
  • Using nested loops causing slow performance
  • Sorting array which changes element order
  • Calculating average instead of max sum
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard