Sliding Window
Minimum Size Subarray Sum (Medium)
Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead. Assume 1 <= nums[i].
def minSubArrayLen(target: int, nums: List[int]) -> int: answer = float("inf") left = right = 0 currSum = 0 # Expand until target found. Shrink until target lost while right < len(nums): currSum += nums[right] right += 1 while currSum >= target: answer = min(answer, right - left) currSum -= nums[left] left += 1 return 0 if answer == float("inf") else answer
Time: O(n)
Space: O(1)
Longest Substring Without Repeating Characters (Medium)
Given a string s, find the length of the longest substring without repeating characters.
def lengthOfLongestSubstring(s: str) -> int: cSet = set() answer = 0 left = 0 # Expand window for right in range(len(s)): # Shrink window if duplicate found while s[right] in cSet: cSet.remove(s[left]) left += 1 cSet.add(s[right]) answer = max(answer, right - left + 1) return answer
Time: O(n)
Space: O(n)