The variable-size sliding window algorithm is one of the most efficient techniques for solving problems involving subarrays or substrings that must satisfy certain conditions. Unlike a fixed-size window, the variable-size version dynamically expands and contracts based on constraints such as sum, distinct characters, or allowed types.
In coding interviews, mastering this approach is a big advantage — especially for problems that seem to require nested loops but can be solved in linear time.
In this article, we’ll go through five popular LeetCode problems that use this pattern. You’ll see clear explanations and Java code.
Table of Contents
Problem 1: Longest Substring Without Repeating Characters (LeetCode 3) – Variable-Size Sliding Window Solution
Problem Statement:
Given a string s, find the length of the longest substring without repeating characters.
Leetcode Problem: Longest Substring Without Repeating Characters
Example:
Input: s = “abcabcbb“
Output: 3
Explanation: “abc” is the longest substring without repeating characters.

Approach — Variable-Size Sliding Window:
- Use two pointers (start and end) to define the current window for the variable-size sliding window.
- Keep a Set of characters in the current window.
- Expand the end pointer until a duplicate is found.
- When a duplicate appears, shrink the window from start until the duplicate is removed.
- Track the maximum length along the way.
Java Code:
import java.util.*; public class LongestSubstringNoRepeat { public static int lengthOfLongestSubstring(String s) { Set<Character> set = new HashSet<>(); int start = 0, maxLen = 0; for (int end = 0; end < s.length(); end++) { while (set.contains(s.charAt(end))) { set.remove(s.charAt(start)); start++; } set.add(s.charAt(end)); maxLen = Math.max(maxLen, end - start + 1); } return maxLen; } public static void main(String[] args) { String s = "abcabcbb"; System.out.println(lengthOfLongestSubstring(s)); // Output: 3 } }
For the above example, here’s a visual representation of how the fixed-size sliding window algorithm works. Click the arrows to view the steps one by one.
Why It Works:
The window expands to include new characters and contracts only when a duplicate appears, ensuring each character is processed at most twice — making it O(n).
Also check: Heap Sort Algorithm Explained: A Beginner Friendly Guide with Leetcode Solutions In Java
Problem 2: Minimum Size Subarray Sum (LeetCode 209) – Variable-Size Sliding Window Solution
Problem Statement:
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is greater than or equal to target. If no such subarray exists, return 0.
Leetcode Problem: Minimum Size Subarray Sum
Example:
Input: nums = [2,3,1,2,4,3], target = 7
Output: 2
Explanation: [4,3] is the smallest subarray with sum ≥ 7.
Approach — Variable-Size Sliding Window:
- Initialize start = 0 and sum = 0.
- Expand end until sum >= target. This explains the variable-size sliding window.
- Once the condition is met, shrink from the left to try to minimize the length.
- Update the result with the smallest length found.
Java Code:
public class MinSubArrayLen { public static int minSubArrayLen(int target, int[] nums) { int start = 0, sum = 0, minLen = Integer.MAX_VALUE; for (int end = 0; end < nums.length; end++) { sum += nums[end]; while (sum >= target) { minLen = Math.min(minLen, end - start + 1); sum -= nums[start]; start++; } } return (minLen == Integer.MAX_VALUE) ? 0 : minLen; } public static void main(String[] args) { int[] nums = {2,3,1,2,4,3}; int target = 7; System.out.println(minSubArrayLen(target, nums)); // Output: 2 } }
Problem 3: Longest Substring with At Most K Distinct Characters (LeetCode 340) – Variable-Size Sliding Window Solution
Problem Statement:
Given a string s and an integer k, return the length of the longest substring that contains at most k distinct characters.
Leetcode Problem: Longest Substring with At Most K Distinct Characters
Example:
Input: s = “eceba“, k = 2
Output: 3
Explanation: “ece” is the longest substring with at most 2 distinct characters.
Approach — Variable-Size Sliding Window:
- Use a Map<Character, Integer> to store character frequencies.
- Expand the window by moving end forward. This is the core of a variable-size sliding window.
- If the number of distinct characters exceeds k, shrink the window from the left.
- Update the max length whenever the condition is valid.
Java Code:
import java.util.*; public class LongestSubstringKDistinct { public static int lengthOfLongestSubstringKDistinct(String s, int k) { Map<Character, Integer> map = new HashMap<>(); int start = 0, maxLen = 0; for (int end = 0; end < s.length(); end++) { map.put(s.charAt(end), map.getOrDefault(s.charAt(end), 0) + 1); while (map.size() > k) { char leftChar = s.charAt(start); map.put(leftChar, map.get(leftChar) - 1); if (map.get(leftChar) == 0) { map.remove(leftChar); } start++; } maxLen = Math.max(maxLen, end - start + 1); } return maxLen; } public static void main(String[] args) { String s = "eceba"; int k = 2; System.out.println(lengthOfLongestSubstringKDistinct(s, k)); // Output: 3 } }
Also check: Greedy Algorithm: A Comprehensive Guide With Examples
Problem 4: Fruit Into Baskets (LeetCode 904) – Variable-Size Sliding Window Solution
Problem Statement:
You are visiting a row of fruit trees, represented by an integer array fruits, where fruits[i] is the type of fruit the i-th tree produces. You can only carry at most two types of fruit. Return the maximum number of fruits you can pick in a single trip.
Leetcode Problem: Fruit Into Baskets
Example:
Input: fruits = [1,2,1]
Output: 3
Explanation: You can pick all 3 fruits since they are of at most 2 types.
Approach — Variable-Size Sliding Window:
- Same as “at most K distinct characters” but applied to integers with k = 2.
- Use a map to store fruit counts.
- Expand while you have ≤ 2 types, shrink otherwise. This step explains the variable-size sliding window.
- Track the maximum window length.
Java Code:
import java.util.*; public class FruitIntoBaskets { public static int totalFruit(int[] fruits) { Map<Integer, Integer> map = new HashMap<>(); int start = 0, maxLen = 0; for (int end = 0; end < fruits.length; end++) { map.put(fruits[end], map.getOrDefault(fruits[end], 0) + 1); while (map.size() > 2) { int leftFruit = fruits[start]; map.put(leftFruit, map.get(leftFruit) - 1); if (map.get(leftFruit) == 0) { map.remove(leftFruit); } start++; } maxLen = Math.max(maxLen, end - start + 1); } return maxLen; } public static void main(String[] args) { int[] fruits = {1,2,1}; System.out.println(totalFruit(fruits)); // Output: 3 } }
Problem 5: Subarray Product Less Than K (LeetCode 713) – Variable-Size Sliding Window Solution
Problem Statement:
Given an array of positive integers nums and an integer k, return the number of contiguous subarrays where the product of all elements in the subarray is less than k.
Leetcode Problem: Subarray Product Less Than K
Example
Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Approach — Variable-Size Sliding Window:
- Keep a product of elements in the current window.
- Expand the window by moving end.
- If product ≥ k, shrink from the left by moving start until product < k.
- Count the subarrays formed with each window expansion.
Java Code:
public class SubarrayProductLessThanK { public static int numSubarrayProductLessThanK(int[] nums, int k) { if (k <= 1) return 0; // No subarray can have product < 1 int start = 0, count = 0; long product = 1; for (int end = 0; end < nums.length; end++) { product *= nums[end]; while (product >= k) { product /= nums[start]; start++; } // Number of new subarrays ending at 'end' count += end - start + 1; } return count; } public static void main(String[] args) { int[] nums = {10, 5, 2, 6}; int k = 100; System.out.println(numSubarrayProductLessThanK(nums, k)); // Output: 8 } }
Why It Works
- Positive numbers ensure that expanding the window increases the product and shrinking decreases it, so the sliding window logic works perfectly.
- Each element is processed at most twice → O(n) time complexity.
Conclusion
These five LeetCode problems are staples in coding interviews and perfectly illustrate the power of the variable-size sliding window technique:
- LeetCode 3 – Manage duplicates in substrings.
- LeetCode 209 – Shrink to meet a sum constraint.
- LeetCode 340 – Control the number of distinct elements.
- LeetCode 904 – Adapt to real-world constraints like two types of items.
- LeetCode 713 – Maintaining a shrinking/expanding window using product.
By practicing these, you’ll develop the intuition to recognize when to expand and contract your window, turning O(n²) problems into O(n) solutions.
That’s all on 5 problems and their solutions based on the variable-size sliding window algorithm.
To keep yourself up to date with our latest content, please subscribe to our newsletter by dropping your email address here: Signup for Our Newsletter.
Please follow us on Medium.
Further Reading
- How to crack technical interview – Google, Amazon & more
- How to Prepare for and Crack the Coding Interview
- Machine Coding Round – What is it & how to crack it
- Digital Wallet Design – Machine Coding Round Solution
- Best Coding Platform To Become A Coding Expert
- The ultimate guide to interview preparation