Skip to content

renzrollon/sliding-window-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Sliding Window — Java

A collection of classic sliding-window algorithm problems implemented in Java. Each solution uses the sliding-window technique for O(n) time and O(1) auxiliary space.

Problems

1. Smallest Subarray with a Given Sum

Given an array of positive integers and a target sum S, find the length of the smallest contiguous subarray whose sum is ≥ S. Returns 0 if no such subarray exists.

Technique: Dynamic (variable-size) sliding window with two pointers.

int result = SmallestSubarrayWithGivenSum.findSmallestSubarrayLength(new int[]{2, 1, 5, 2, 3, 2}, 7);
// result = 2  (subarray [5, 2])
Complexity Value
Time O(n) — each element enters and leaves the window at most once
Space O(1) — only scalar variables

2. Find All Anagrams in a String

Given a string s and a pattern p, find all starting indices in s where an anagram of p begins.

Technique: Fixed-size sliding window with int[26] character frequency arrays.

List<Integer> result = FindAllAnagramsInAString.findAnagrams("cbaebabacd", "abc");
// result = [0, 6]
Complexity Value
Time O(n) — single pass with O(1) comparison per step
Space O(1) — two fixed-size int[26] arrays (output list not counted)

Project Structure

src/
  main/java/com/slidingwindow/
    SmallestSubarrayWithGivenSum.java
    FindAllAnagramsInAString.java
  test/java/com/slidingwindow/
    SmallestSubarrayWithGivenSumTest.java
    FindAllAnagramsInAStringTest.java

Prerequisites

  • Java 17+
  • Maven 3.x

Build & Test

# Compile
mvn compile

# Run all tests
mvn test

Sliding Window Patterns

This project demonstrates two common sliding-window patterns:

Pattern Window Size Use Case Example
Variable-size Shrinks/grows dynamically Optimization (min/max length) Smallest subarray with sum ≥ S
Fixed-size Constant (p.length()) Matching/counting Find all anagrams

How It Works

Variable-size window (Smallest Subarray):

  1. Expand right pointer to grow the window
  2. When constraint is met (sum ≥ S), shrink from left to find the minimum
  3. Each element enters and leaves the window at most once → O(n)

Fixed-size window (Anagram Finder):

  1. Build frequency array for the pattern
  2. Initialize window of size p.length()
  3. Slide one character at a time: add incoming, remove outgoing
  4. Compare frequency arrays after each slide → O(1) per step

Tech Stack

Tool Version Purpose
Java 17 Language
Maven 3.x Build system
JUnit Jupiter 5.11.4 Test framework
Maven Surefire 3.5.2 Test runner

About

Exercise for sliding-window pattern using Java and Spec Driven Development

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages