Sliding Window

O(n)
n = size(array)

Python: Shrinkable | Java: Shrinkable

# i
# nums: [5,7,2,8]
# j
def longestWindow(nums: List[int]) -> int:
j = 0, ans
for i in range(nums):
# code using nums[i] to update the state
# that might invalidate the window
while invalid():
# code using nums[j] to update the state
# and shrink the left edge while the window is invalid
j += 1
# longest window so far = len([i, j])
ans = max(ans, i - j + 1);
return ans
// i
// nums: [5,7,2,8]
// j
int longestWindow(int[] nums) {
int max;
for (int i = 0, j = 0; i < nums.length; i++) {
// code using nums[i] to update the state
// that might invalidate the window
for (; invalid(); j++) {
// code using nums[j] to update the state
// and shrink the left edge while the window is invalid
}
// longest window so far = length([i, j])
max = max(ans, i - j + 1);
}
return max;
}
# i
# nums: [5,7,2,8]
# j
def longestWindow(nums: List[int]) -> int:
i = j = 0;
for i in range(nums):
# code using nums[i] to update the state
# that might invalidate the window
if invalid():
# code using nums[j] to update the state
# and shift the window sideways.
# the window grows if the state is valid
# and shifts if it's invalid.
j += 1
# the maximum size of the window
return i - j
// i
// nums: [5,7,2,8]
// j
int longestWindow(int[] nums) {
int i = 0, j = 0;
for (; i < nums.length; i++) {
// code using nums[i] to update the state
// that might invalidate the window
if (invalid()) {
// code using nums[j] to update the state
// and shift the window sideways.
// the window grows if the state is valid
// and shifts if it's invalid.
j++;
}
}
return i - j; // the maximum size of the window
}
 
Next
Next

Binary Search