QA
Beginner LevelData Structures & Algorithms

What is the Sliding Window Technique?

ā“ Interview Prompt: Explain the Sliding Window pattern, fixed vs variable window, and solve the Maximum Sum Subarray of size K problem.

The Sliding Window technique maintains a window (contiguous sub-array/sub-string) and slides it across the input, avoiding redundant recomputation.

Fixed Window (size K):

Slide the window by adding the next element and removing the oldest one.

•
Time: $O(N)$, Space: $O(1)$.

Variable Window:

Expand the right pointer; shrink the left pointer when a constraint is violated.

•
Used for: Longest substring without repeating characters, smallest subarray with sum ≄ target.

Code Implementation Example

typescript
// Max sum subarray of size K — O(N)
function maxSumSubarray(arr: number[], k: number): number {
  let windowSum = 0, maxSum = -Infinity;

  for (let i = 0; i < arr.length; i++) {
    windowSum += arr[i];
    if (i >= k - 1) {
      maxSum = Math.max(maxSum, windowSum);
      windowSum -= arr[i - (k - 1)]; // slide: remove leftmost
    }
  }
  return maxSum;
}

console.log(maxSumSubarray([2, 1, 5, 1, 3, 2], 3)); // 9 (5+1+3)
šŸ’”Fixed sliding window computing maximum subarray sum in O(N).
šŸŽÆ Interview Key Takeaway

Sliding Window converts O(N²) brute-force subarray problems into O(N) by maintaining a running computation as the window moves.

#DSA#Sliding Window#Patterns#Subarray#Beginner
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?