Practice question from Sliding Window Patterns

Fill-in: A fixed-size sliding window of size k=3 on array [2,1,5,1,3,2] performs the first slide from window [2,1,5] to [1,5,1]. How many arithmetic operations (additions/subtractions) does this single slide require?

Answer

2

Explanation

Sliding requires exactly 2 operations: subtract the element leaving (arr[0]=2) and add the element entering (arr[3]=1). This is the key optimization of sliding window: window_sum = window_sum - 2 + 1. Without sliding window, recalculating the sum would require k=3 additions.

More questions from Mastering Leet Code Algorithms