java
43 lines · 8 steps
The sliding window technique in Java
Find the best fixed-length subarray in one pass by adding and removing one element at a time instead of resumming.
Explained by
highlit
1import java.util.Arrays;
2
3public class SlidingWindow {
4 // Returns the maximum sum of any contiguous subarray of length k.
5 public static long maxSubarraySum(int[] nums, int k) {
6 if (nums == null || k <= 0 || k > nums.length) {
7 throw new IllegalArgumentException(
8 "k must be between 1 and " + (nums == null ? 0 : nums.length));
9 }
10
11 long windowSum = 0;
12 for (int i = 0; i < k; i++) {
13 windowSum += nums[i];
14 }
15
16 long maxSum = windowSum;
17 for (int end = k; end < nums.length; end++) {
18 // Slide the window: add the entering element, drop the leaving one.
19 windowSum += nums[end] - nums[end - k];
20 maxSum = Math.max(maxSum, windowSum);
21 }
22 return maxSum;
23 }
24
25 // Variant: also report where the best window starts.
26 public static int[] maxSubarrayRange(int[] nums, int k) {
27 long windowSum = 0;
28 for (int i = 0; i < k; i++) {
29 windowSum += nums[i];
30 }
31
32 long maxSum = windowSum;
33 int bestStart = 0;
34 for (int end = k; end < nums.length; end++) {
35 windowSum += nums[end] - nums[end - k];
36 if (windowSum > maxSum) {
37 maxSum = windowSum;
38 bestStart = end - k + 1;
39 }
40 }
41 return Arrays.copyOfRange(nums, bestStart, bestStart + k);
42 }
43}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Maintaining a running sum and updating it incrementally turns an O(n*k) brute force into a single O(n) pass.
- 2Validating arguments up front keeps the core loop simple and surfaces misuse clearly.
- 3Tracking the index where the best result occurs costs almost nothing and lets you return the window itself, not just its score.
Related explainers
java
public class ThumbnailProcessor { private static final int MAX_CONCURRENCY = 4;
Bounded parallel thumbnail rendering in Java
concurrency
thread-pool
futures
Intermediate
7 steps
java
public class SortedListMerger { public static int[] merge(int[] a, int[] b) { int[] result = new int[a.length + b.length];
Merging two sorted arrays in Java
two-pointers
merging
arrays
Beginner
6 steps
python
import time from collections import defaultdict from threading import Lock
Sliding-window login rate limiting in Flask
rate-limiting
sliding-window
thread-safety
Intermediate
7 steps
java
import java.util.ArrayDeque; import java.util.Deque; public final class RollingAverage {
A rolling average over a sliding window
sliding-window
running-sum
deque
Intermediate
7 steps
java
@Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = StrongPasswordValidator.class) @Documented
Building a custom @StrongPassword validator in Spring
bean-validation
annotations
regex
Intermediate
7 steps
java
@Component public class JwtAuthenticationFilter extends OncePerRequestFilter { private final JwtTokenProvider tokenProvider;
How a JWT auth filter works in Spring
authentication
jwt
servlet-filter
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/the-sliding-window-technique-in-java-explained-java-536c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.