Sliding window Flashcards

(6 cards)

1
Q

LeetCode 121 – Best Time to Buy and Sell Stock
Max profit from one buy/sell.

A

Single pass; track minPriceSoFar and best = max(best, price - minPriceSoFar).

Sliding “anchor” is the min so far.

Time O(n), Space O(1).

Tags: One-pass, Sliding Anchor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

LeetCode 3 – Longest Substring w/o Repeats
Length of longest substring with all unique chars.

A

Expand right, count chars; when a char repeats, shrink left until valid.

Map/array to store last index or freq.

Maintain best = max(best, windowLen).

Time O(n), Space O(Σ).

Tags: Sliding Window, Hash Map.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

LeetCode 424 – Longest Repeating Char Replacement
With at most k replacements, longest substring of same char.

A

Window expands; track maxFreq of any char in window.

If windowLen - maxFreq > k, shrink from left.

Answer is max window size seen.

Time O(n), Space O(Σ).

Tags: Sliding Window, Frequency, “keep maxFreq”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

LeetCode 567 – Permutation in String
Does s2 contain a permutation of s1?

A

Need a window of size len(s1) with identical char counts.

Maintain freq diff (or two arrays) and a matches counter.

Slide fixed-size window over s2; if all counts zero / matches==Σ → true.

Time O(n + m), Space O(Σ).

Tags: Fixed-size Window, Frequency Match.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

LeetCode 76 – Minimum Window Substring
Smallest window in s containing all chars of t.

A

Need counts of t. Expand right, decrement need; when all met, try to shrink from left to minimal.

Track best [L,R].

Careful with duplicates and zero/negative counts.

Time O(n), Space O(Σ).

Tags: Sliding Window, Two Pointers, “expand then contract”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

LeetCode 239 – Sliding Window Maximum
Max of each window of size k.

A

Monotonic deque of indices (values decreasing).

Pop back while nums[i] ≥ tail; push i.

Pop front if out of window (i - k + 1).

Front is max for current window.

Time O(n), Space O(k).

Tags: Monotonic Queue, Fixed-size Window.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly