Introduction
The Sliding Window Technique is one of the most important concepts in Data Structures and Algorithms (DSA). It is widely used to solve array and string problems efficiently.
A very popular interview problem based on this technique is Longest Substring Without Repeating Characters. This problem checks your understanding of strings, pointers, and hashing.
In this article, the material is explained in simple terms, making it easy for beginners to understand.
What is the Sliding Window Technique?
The Sliding Window Technique is used when we process continuous segments of an array or string.
Instead of recalculating values repeatedly, we maintain a window and slide it forward under specified conditions.
This technique helps reduce time complexity from slow approaches to faster ones.
Types of Sliding Windows
There are two common types of sliding windows:
Fixed Size Window – Window size remains constant
Variable Size Window – Window size changes based on conditions
The Longest Substring Without Repeating Characters uses a variable-size sliding window.
Problem Statement
Given a string, find the length of the longest substring that does not contain any repeating characters.
Example
Input: "abcabcbb"
Output: 3
Explanation
The longest substring without repeating characters is "abc", which has a length of 3.
Brute Force Approach (Not Efficient)
In the brute-force method, we check all possible substrings and verify whether they contain repeating characters.
Drawbacks
Too many substrings
Time Complexity becomes O(n²) or worse
This approach is not suitable for interviews.
Optimized Approach Using Sliding Window
To solve this problem efficiently, we use:
Two pointers (left and right)
A HashSet or HashMap to track characters
The idea is to expand the window until a duplicate character appears, then shrink the window.
Step-by-Step Explanation
Steps:
Initialize two pointers
leftandrightUse a set to store unique characters
Move
rightpointer forwardIf character is already present, remove characters from the left
Update the maximum window size
This ensures all characters inside the window are unique.
Dry Run Example
String: "abcabcbb"
Join the conversation! Your thoughts help the community grow.