1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Fixed Sliding Window
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
11Hrs
40Mins
50Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Fixed Sliding Window

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
11Hrs
40Mins
50Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
    • Java + DSA
    • Full Stack Web Dev
    • AI/ML + Python
  • 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

Fixed Sliding Window

Overview

The Sliding Window is a subset of the Two Pointers pattern, specifically designed to solve problems involving Subarrays or Substrings.

A Fixed Sliding Window is used when the problem asks you to analyze a subarray of a specific, unchanging size (e.g., 'Find the maximum sum of any 3 consecutive elements').

A naive approach would use nested loops: for every element, start an inner loop to add the next 3 elements (O(NK) time). The Sliding Window approach realizes that as the window moves one step to the right, almost all the data remains exactly the same! You simply subtract the element that fell out of the left side of the window, and add the new element that entered the right side. This drops the time complexity to a strict O(N)*.

Syntax

Max Sum Subarray of Size K
java
public class FixedSlidingWindow {
    // Find the maximum sum of any contiguous subarray of size K
    public static int maxSumSubarray(int[] arr, int k) {
        if (arr.length < k) return -1; // Edge case
        
        int maxSum = Integer.MIN_VALUE;
        int currentWindowSum = 0;
        
        for (int i = 0; i < arr.length; i++) {
            // 1. Add the newest element to the window
            currentWindowSum += arr[i];
            
            // 2. Only check sums and slide if we've hit window size K
            if (i >= k - 1) {
                // Record the maximum seen so far
                maxSum = Math.max(maxSum, currentWindowSum);
                
                // Slide the window forward by subtracting the oldest element
                // The oldest element is at index (i - (k - 1))
                currentWindowSum -= arr[i - (k - 1)];
            }
        }
        
        return maxSum;
    }
}

Common Pitfalls

  • Off-by-one errors in window sizing. The formula to find the oldest element leaving the window is i - (k - 1). If you accidentally do i - k, you will subtract an element that is still supposed to be inside the window, destroying your calculations.
  • Recalculating the entire window. The whole point of this pattern is to AVOID recalculating. If you have an inner for loop inside your window logic calculating the sum from scratch every time, you have failed to implement the pattern and are running in O(N*K) time.
  • Failing to handle arrays smaller than K. If arr.length < k, the window can never form. If you don't check for this edge case at the start of the method, your math will break or return incorrect defaults.

Interview Questions

How do you identify that a problem requires a Fixed Sliding Window?

Look for three keywords in the prompt: 1) 'Contiguous', 'Subarray', or 'Substring'. 2) A specific size or length constraint 'K'. 3) A requirement to find a maximum, minimum, or average.

What is the time complexity of a Fixed Sliding Window?

O(N). The algorithm processes every element in the array exactly once. Adding to the window is an O(1) operation, and subtracting from the window is an O(1) operation.

Real-World Example

Network Traffic Rate Limiting. A server allows a maximum of 100 requests per 1-second rolling window. A sliding window algorithm continuously adds new incoming requests to a counter, and subtracts requests that fall outside the 1000ms window, allowing the server to instantly reject traffic spikes in O(1) real-time.

example
java
// Conceptual Rate Limiting
int currentRequests = 0;
// Add new request
currentRequests += newRequestSize;
// Subtract requests older than 1 second
currentRequests -= oldRequestsLeavingWindow;

if (currentRequests > LIMIT) {
    throw new RateLimitExceededException();
}

Check Your Knowledge

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

Question 1

What makes the Sliding Window pattern so efficient?

Question 2

If `i` is the current end of a window of size `K`, what is the index of the element that needs to be subtracted?

Question 3

Which of these problems is a perfect fit for a Fixed Sliding Window?

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

Fixed Sliding Window

Overview

The Sliding Window is a subset of the Two Pointers pattern, specifically designed to solve problems involving Subarrays or Substrings.

A Fixed Sliding Window is used when the problem asks you to analyze a subarray of a specific, unchanging size (e.g., 'Find the maximum sum of any 3 consecutive elements').

A naive approach would use nested loops: for every element, start an inner loop to add the next 3 elements (O(NK) time). The Sliding Window approach realizes that as the window moves one step to the right, almost all the data remains exactly the same! You simply subtract the element that fell out of the left side of the window, and add the new element that entered the right side. This drops the time complexity to a strict O(N)*.

Syntax

Max Sum Subarray of Size K
java
public class FixedSlidingWindow {
    // Find the maximum sum of any contiguous subarray of size K
    public static int maxSumSubarray(int[] arr, int k) {
        if (arr.length < k) return -1; // Edge case
        
        int maxSum = Integer.MIN_VALUE;
        int currentWindowSum = 0;
        
        for (int i = 0; i < arr.length; i++) {
            // 1. Add the newest element to the window
            currentWindowSum += arr[i];
            
            // 2. Only check sums and slide if we've hit window size K
            if (i >= k - 1) {
                // Record the maximum seen so far
                maxSum = Math.max(maxSum, currentWindowSum);
                
                // Slide the window forward by subtracting the oldest element
                // The oldest element is at index (i - (k - 1))
                currentWindowSum -= arr[i - (k - 1)];
            }
        }
        
        return maxSum;
    }
}

Common Pitfalls

  • Off-by-one errors in window sizing. The formula to find the oldest element leaving the window is i - (k - 1). If you accidentally do i - k, you will subtract an element that is still supposed to be inside the window, destroying your calculations.
  • Recalculating the entire window. The whole point of this pattern is to AVOID recalculating. If you have an inner for loop inside your window logic calculating the sum from scratch every time, you have failed to implement the pattern and are running in O(N*K) time.
  • Failing to handle arrays smaller than K. If arr.length < k, the window can never form. If you don't check for this edge case at the start of the method, your math will break or return incorrect defaults.

Interview Questions

How do you identify that a problem requires a Fixed Sliding Window?

Look for three keywords in the prompt: 1) 'Contiguous', 'Subarray', or 'Substring'. 2) A specific size or length constraint 'K'. 3) A requirement to find a maximum, minimum, or average.

What is the time complexity of a Fixed Sliding Window?

O(N). The algorithm processes every element in the array exactly once. Adding to the window is an O(1) operation, and subtracting from the window is an O(1) operation.

Real-World Example

Network Traffic Rate Limiting. A server allows a maximum of 100 requests per 1-second rolling window. A sliding window algorithm continuously adds new incoming requests to a counter, and subtracts requests that fall outside the 1000ms window, allowing the server to instantly reject traffic spikes in O(1) real-time.

example
java
// Conceptual Rate Limiting
int currentRequests = 0;
// Add new request
currentRequests += newRequestSize;
// Subtract requests older than 1 second
currentRequests -= oldRequestsLeavingWindow;

if (currentRequests > LIMIT) {
    throw new RateLimitExceededException();
}

Check Your Knowledge

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

Question 1

What makes the Sliding Window pattern so efficient?

Question 2

If `i` is the current end of a window of size `K`, what is the index of the element that needs to be subtracted?

Question 3

Which of these problems is a perfect fit for a Fixed Sliding Window?

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