Sliding window Flashcards
(5 cards)
What is the Sliding Window pattern and when is it used?
Maintains a variable-size window sliding over array/string to find subarrays.
Use Case: Contiguous subarray/substring problems (e.g., max sum)
Example: [Trapping Rain Water].
What are the key steps in the Sliding Window pattern?
- Initialize left/right pointers.
- Expand right until condition met.
- Shrink left to optimize.
- Track result (e.g., max length).
Explain steps for [Trapping Rain Water] aloud.
How does the Sliding Window pattern apply to [Trapping Rain Water]?
Compute water trapped between bars.
Approach: Use two pointers to track max heights, calculate water at lowe
Example: [Trapping Rain Water].
What are the complexity and gotchas of the Sliding Window pattern?
Time: O(n), Space: O(1).
Gotchas: Empty array, invalid window (e.g., k=0).
List edge cases for [Trapping Rain Water] aloud.
Code example of the Sliding Window pattern.
```python
from typing import List
def trap(height: List[int]) -> int:
left, right, water = 0, len(height)-1, 0
max_left, max_right = 0, 0
while left < right:
max_left = max(max_left, height[left])
max_right = max(max_right, height[right])
if max_left <= max_right:
water += max_left - height[left]
left += 1
else:
water += max_right - height[right]
right -= 1
return water
~~~