HardLeetCode #239Sliding Window
Sliding Window Maximum
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Constraints
1 <= nums.length <= 10^5, -10^4 <= nums[i] <= 10^4, 1 <= k <= nums.length
Examples
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Solution Approach
Maintain a window of elements with a specific property. Expand window by moving right pointer, contract by moving left pointer when condition is violated. Use HashMap/Set to track elements in current window.
Implementation
def lengthOfLongestSubstring(s):
char_map = {}
max_length = 0
left = 0
for right in range(len(s)):
if s[right] in char_map:
left = max(left, char_map[s[right]] + 1)
char_map[s[right]] = right
max_length = max(max_length, right - left + 1)
return max_lengthComplexity Analysis
Time Complexity
O(n)Space Complexity
O(min(m, n))Key Learning Points
Maintain valid window with two pointersUse HashMap for character trackingExpand right, contract left when needed
Related Problems to Practice
Minimum Window SubstringSliding Window MaximumSubarrays with K Different Integers
Complexity
Time:O(n)
Space:O(min(m, n))
Hints
- 1.A naive approach is O(nk), can we do better?
- 2.Use a deque to maintain potential maximums
- 3.Keep deque in decreasing order
Asked at
Google