πŸ“Š Sliding Window Problems


Welcome to the Sliding Window section of JDCodebase!

The Sliding Window technique is one of the most powerful tools to optimize brute-force solutions for problems involving arrays or strings. It helps reduce nested loops and improve time complexity from O(nΒ²) to O(n) in many real-world DSA problems.

πŸ” What is Sliding Window?

It’s a technique where you maintain a window (subarray or substring) that slides over the input data to process only the required portion at a time. You either:

  • Fix the size of the window (e.g., size = k)
  • Or vary the window dynamically based on conditions

πŸ€” When to Use Sliding Window?

  • Subarrays/substrings with max/min sum, length, or frequency
  • Count of distinct/repeating elements in a window
  • Checking existence of patterns in a range (e.g., anagrams)
  • Problems that ask for optimal results over consecutive elements

βš™οΈ How Sliding Window Works?

  • Initialize two pointers – left and right
  • Expand the window by moving the right pointer
  • Shrink the window by moving the left pointer when constraints are violated
  • Update the result (max/min/count) during the process

🧠 Common Patterns

  • Maximum sum of subarray of size k
  • Longest substring with k distinct characters
  • Smallest subarray with a sum β‰₯ target
  • Find all anagrams of a pattern in a string
  • Longest substring without repeating characters

πŸ“ Problems List

  1. Contains Duplicate II (#219)
  2. Longest Harmonious Subsequence (#594)
  3. Maximum Average Subarray I (#643)