What is the sliding window technique?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Data Structures & Algorithms topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
The sliding window technique maintains a "window" (subarray or substring) between two pointers that slides through the data, avoiding repeated computation by updating the window's result incrementally as it moves. Types: (1) Fixed-size window: window of size k slides one step at a time. Maximum sum of k consecutive elements: compute first window sum, then subtract leftmost and add new rightmost element — O(n) instead of O(n×k); (2) Variable-size window (expand/contract): right pointer expands, left pointer contracts when a condition is violated. Longest Substring Without Repeating Characters: expand right, if duplicate found, contract from left until no duplicate. Template: left=0; for(right=0; right<n; right++){ window.add(arr[right]); while(window is invalid){ window.remove(arr[left]); left++; } update result; }. Key insight: use a hash map to track window contents for O(1) add/remove. Time: O(n) — each element enters and exits the window at most once. Applications: Maximum of every subarray (use deque), Minimum Window Substring, Permutation in String, Fruit Into Baskets, Count of subarrays with product less than K. Sliding window is essential for substring/subarray optimization problems.
Pro Tip
This topic has Data Structures & Algorithms-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.