1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Variable Sliding Window
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
01Hrs
21Mins
56Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Variable Sliding Window

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
01Hrs
21Mins
56Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Variable Sliding Window

Overview

The Variable Sliding Window is a more complex evolution of the fixed window. Instead of the window size being locked to 'K', the window size dynamically expands and shrinks based on a specific condition.

The logic operates like a caterpillar: 1. The right pointer (head) moves forward, expanding the window and adding data until the window violates a condition. 2. Once the condition is violated, the left pointer (tail) moves forward, shrinking the window and removing data until the condition is satisfied again.

This pattern is used when you are asked to find the Longest or Shortest contiguous subarray that meets a target condition (e.g., 'Find the longest substring without repeating characters' or 'Find the smallest subarray whose sum is >= Target').

Syntax

Smallest Subarray with sum >= target
java
public class VariableSlidingWindow {
    // Problem: Find length of the smallest contiguous subarray whose sum is >= target
    public static int minSubArrayLen(int target, int[] nums) {
        int minLength = Integer.MAX_VALUE;
        int currentSum = 0;
        int left = 0; // Tail of the caterpillar
        
        // right is the head of the caterpillar
        for (int right = 0; right < nums.length; right++) {
            // Expand the window to the right
            currentSum += nums[right];
            
            // While the condition is met, try to shrink it from the left 
            // to find the SMALLEST possible window!
            while (currentSum >= target) {
                // Record the valid window size
                minLength = Math.min(minLength, right - left + 1);
                
                // Shrink the window: subtract the left element and move tail forward
                currentSum -= nums[left];
                left++;
            }
        }
        
        return minLength == Integer.MAX_VALUE ? 0 : minLength;
    }
}

Common Pitfalls

  • Using an if statement instead of a while loop for shrinking. When the window becomes invalid, shrinking the left side by just 1 step might not be enough to make it valid again. You must always use a while(condition) loop to continuously shrink the left side until validity is restored.
  • Calculating window length incorrectly. The formula for the number of elements in a window bounded by left and right indices is ALWAYS right - left + 1. Forgetting the + 1 is a guaranteed bug.
  • Applying this pattern to arrays with negative numbers (for sum problems). If the problem involves finding a target sum and the array contains negative numbers, expanding the window doesn't guarantee the sum increases, destroying the caterpillar logic. You must use Prefix Sums + HashMaps instead.

Interview Questions

Why is the time complexity of Variable Sliding Window O(N) even though there is a while loop nested inside a for loop?

Because both the left and right pointers only ever move forward. The right pointer iterates over the array once. The left pointer iterates over the array at most once. Therefore, each element is processed a maximum of twice (added once, removed once). 2N operations is O(N) time complexity.

How do you solve 'Longest Substring Without Repeating Characters'?

Use a Variable Sliding Window with a HashSet. The right pointer adds characters to the set. If it hits a character already in the set, the condition is violated. The left pointer must then continuously remove characters from the set and shrink the window until that duplicate character is ejected.

Real-World Example

Data Compression Algorithms (like LZ77 used in ZIP and PNG files) use dynamic sliding windows. The algorithm scans a file and looks backwards in a sliding window to find the longest exact match of the data it is currently looking at. If it finds a match, it replaces the current data with a short pointer to the previous occurrence, compressing the file.

example
java
// Conceptual LZ77 Window Match
int windowSize = findLongestMatchInWindow(data, currentPosition, slidingWindow);
if (windowSize > 3) {
    writeCompressionPointer(windowSize);
    currentPosition += windowSize; // Skip ahead
} else {
    writeLiteralByte(data[currentPosition]);
    currentPosition++;
}

Check Your Knowledge

Test your understanding of Variable Sliding Window with these quick questions.

Question 1

When should you use a Variable Sliding Window instead of a Fixed one?

Question 2

What logic must control the `left` pointer in a Variable window?

Question 3

What is the formula to calculate the length of the window between `left` and `right` indices?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Variable Sliding Window

Overview

The Variable Sliding Window is a more complex evolution of the fixed window. Instead of the window size being locked to 'K', the window size dynamically expands and shrinks based on a specific condition.

The logic operates like a caterpillar: 1. The right pointer (head) moves forward, expanding the window and adding data until the window violates a condition. 2. Once the condition is violated, the left pointer (tail) moves forward, shrinking the window and removing data until the condition is satisfied again.

This pattern is used when you are asked to find the Longest or Shortest contiguous subarray that meets a target condition (e.g., 'Find the longest substring without repeating characters' or 'Find the smallest subarray whose sum is >= Target').

Syntax

Smallest Subarray with sum >= target
java
public class VariableSlidingWindow {
    // Problem: Find length of the smallest contiguous subarray whose sum is >= target
    public static int minSubArrayLen(int target, int[] nums) {
        int minLength = Integer.MAX_VALUE;
        int currentSum = 0;
        int left = 0; // Tail of the caterpillar
        
        // right is the head of the caterpillar
        for (int right = 0; right < nums.length; right++) {
            // Expand the window to the right
            currentSum += nums[right];
            
            // While the condition is met, try to shrink it from the left 
            // to find the SMALLEST possible window!
            while (currentSum >= target) {
                // Record the valid window size
                minLength = Math.min(minLength, right - left + 1);
                
                // Shrink the window: subtract the left element and move tail forward
                currentSum -= nums[left];
                left++;
            }
        }
        
        return minLength == Integer.MAX_VALUE ? 0 : minLength;
    }
}

Common Pitfalls

  • Using an if statement instead of a while loop for shrinking. When the window becomes invalid, shrinking the left side by just 1 step might not be enough to make it valid again. You must always use a while(condition) loop to continuously shrink the left side until validity is restored.
  • Calculating window length incorrectly. The formula for the number of elements in a window bounded by left and right indices is ALWAYS right - left + 1. Forgetting the + 1 is a guaranteed bug.
  • Applying this pattern to arrays with negative numbers (for sum problems). If the problem involves finding a target sum and the array contains negative numbers, expanding the window doesn't guarantee the sum increases, destroying the caterpillar logic. You must use Prefix Sums + HashMaps instead.

Interview Questions

Why is the time complexity of Variable Sliding Window O(N) even though there is a while loop nested inside a for loop?

Because both the left and right pointers only ever move forward. The right pointer iterates over the array once. The left pointer iterates over the array at most once. Therefore, each element is processed a maximum of twice (added once, removed once). 2N operations is O(N) time complexity.

How do you solve 'Longest Substring Without Repeating Characters'?

Use a Variable Sliding Window with a HashSet. The right pointer adds characters to the set. If it hits a character already in the set, the condition is violated. The left pointer must then continuously remove characters from the set and shrink the window until that duplicate character is ejected.

Real-World Example

Data Compression Algorithms (like LZ77 used in ZIP and PNG files) use dynamic sliding windows. The algorithm scans a file and looks backwards in a sliding window to find the longest exact match of the data it is currently looking at. If it finds a match, it replaces the current data with a short pointer to the previous occurrence, compressing the file.

example
java
// Conceptual LZ77 Window Match
int windowSize = findLongestMatchInWindow(data, currentPosition, slidingWindow);
if (windowSize > 3) {
    writeCompressionPointer(windowSize);
    currentPosition += windowSize; // Skip ahead
} else {
    writeLiteralByte(data[currentPosition]);
    currentPosition++;
}

Check Your Knowledge

Test your understanding of Variable Sliding Window with these quick questions.

Question 1

When should you use a Variable Sliding Window instead of a Fixed one?

Question 2

What logic must control the `left` pointer in a Variable window?

Question 3

What is the formula to calculate the length of the window between `left` and `right` indices?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A