Algorithm in LeetCode —— Sliding Window

Tips for Sliding Window:

  • The classic way to implement a two-pointer sliding window. The right pointer keeps moving to the right until it can no longer move further (the exact condition depends on the problem). Once the right pointer reaches the far right, start moving the left pointer to shrink the left boundary of the window. Problems 3, 76, 209, 424, 438, 567, 713, 763, 845, 881, 904, 978, 992, 1004, 1040, and 1052.
	left, right := 0, -1

	for left < len(s) {
		if right+1 < len(s) && freq[s[right+1]-'a'] == 0 {
			freq[s[right+1]-'a']++
			right++
		} else {
			freq[s[left]-'a']--
			left++
		}
		result = max(result, right-left+1)
	}
  • Classic sliding window problems: #239 and #480.
TitleSolutionDifficultyTimeSpaceFavorite
3. Longest Substring Without Repeating CharactersGoMediumO(n)O(1)❤️
76. Minimum Window SubstringGoHardO(n)O(n)❤️
239. Sliding Window MaximumGoHardO(n * k)O(n)❤️
424. Longest Repeating Character ReplacementGoMediumO(n)O(1)
480. Sliding Window MedianGoHardO(n * log k)O(k)❤️
567. Permutation in StringGoMediumO(n)O(1)❤️
978. Longest Turbulent SubarrayGoMediumO(n)O(1)❤️
992. Subarrays with K Different IntegersGoHardO(n)O(n)❤️
995. Minimum Number of K Consecutive Bit FlipsGoHardO(n)O(1)❤️
1004. Max Consecutive Ones IIIGoMediumO(n)O(1)
1040. Moving Stones Until Consecutive IIGoMediumO(n log n)O(1)❤️
1052. Grumpy Bookstore OwnerGoMediumO(n log n)O(1)
1074. Number of Submatrices That Sum to TargetGoHardO(n^3)O(n)❤️