Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Sliding Window Technique in DSA | Fixed and Variable Window Strategy



What is the Sliding Window Technique?

The Sliding Window Technique is an optimization strategy for problems involving linear data structures like arrays or strings. It helps reduce the time complexity from O(n²) to O(n) in many cases by avoiding unnecessary re-computation.

Instead of recalculating results for every subarray or substring, we "slide" a window across the structure — updating the result incrementally.

When to Use

Types of Sliding Windows

1. Fixed-size Sliding Window

You know the window size (say k), and the goal is to perform operations over every subarray of size k.

Common Example:

Find the maximum sum of any subarray of size k.

Pseudocode

class SlidingWindowFixed {
    function maxSum(arr, k):
        n = length(arr)
        windowSum = sum of first k elements
        maxSum = windowSum

        for i = k to n-1:
            windowSum = windowSum + arr[i] - arr[i - k]
            maxSum = max(maxSum, windowSum)

        return maxSum
}

Time and Space Complexity

2. Variable-size Sliding Window

Window size changes dynamically based on the conditions. You expand the window by moving the right pointer and shrink it by moving the left pointer until conditions are satisfied.

Common Example:

Find the length of the longest substring with at most K distinct characters.

Pseudocode

class SlidingWindowVariable {
    function longestSubstringWithKDistinct(s, k):
        left = 0
        right = 0
        freqMap = {}
        maxLen = 0

        while right < length(s):
            add s[right] to freqMap
            while size of freqMap > k:
                decrement freqMap[s[left]]
                if freqMap[s[left]] == 0:
                    remove s[left] from freqMap
                left += 1
            maxLen = max(maxLen, right - left + 1)
            right += 1

        return maxLen
}

Time and Space Complexity

Real-World Applications

Example 1: Longest Substring with K Unique Characters

Problem Statement:

Given a string s and an integer k, find the length of the longest substring that contains exactly k unique characters.

For example:

Why Sliding Window?

Using a sliding window is efficient for problems that require processing substrings or subarrays. Instead of generating all substrings and checking each, we maintain a dynamic window with exactly k unique characters and slide it to explore new substrings.

Step-by-step Sliding Window Approach:

  1. Initialize two pointers: left and right for the sliding window.
  2. Use a hash map charCount to count characters in the window.
  3. Expand the window by moving right and updating charCount.
  4. If unique characters exceed k, shrink the window by moving left.
  5. Update the result whenever exactly k unique characters are found.

Pseudocode

// Function to find longest substring with k unique characters
function longestKUniqueSubstring(s, k):
    left = 0
    right = 0
    maxLen = 0
    charCount = empty map

    while right < length of s:
        // Add current character to map
        charCount[s[right]] += 1

        // If unique characters > k, shrink window
        while size of charCount > k:
            charCount[s[left]] -= 1
            if charCount[s[left]] == 0:
                remove s[left] from charCount
            left += 1

        // If exactly k unique characters, update maxLen
        if size of charCount == k:
            maxLen = max(maxLen, right - left + 1)

        right += 1

    return maxLen

Why It Works:

This approach dynamically adjusts the window and ensures that we are always considering substrings with at most k unique characters. When exactly k are present, we update the maximum length seen so far.

Time Complexity:

Space Complexity:

Sliding window techniques like this are crucial in substring problems where the window size or character frequency needs to be tracked. It’s much more efficient than brute-force methods and can be easily adapted to variations of the problem.

Benefits of Sliding Window

Limitations

Conclusion

The Sliding Window technique is a must-know strategy for solving linear structure problems efficiently. It transforms brute-force nested loop solutions into linear-time solutions by reusing previous computations. Mastering fixed and variable window problems unlocks a broad class of optimization problems in DSA interviews and competitive programming.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M