Sliding Window with Two Pointers: A Powerful Technique for Problem Solving
When tackling problems that require working with subsets of data, the sliding window technique with two pointers is an elegant and efficient solution. It’s especially useful when working with strings, arrays, or lists in problems involving subarrays, substrings, or similar concepts.
In this article, we'll explore how the sliding window works and use a common challenge to illustrate its application: Finding the length of the longest substring without repeating characters.
What is the Sliding Window Technique?
The sliding window is a method that involves maintaining a subset of data by using two pointers to define the "window." This window can slide or expand/shrink based on certain conditions. It allows you to optimize problems that would otherwise require brute force.
How Does It Work?
Challenge: Longest Substring Without Repeating Characters
Let’s dive into an example to see this technique in action.
Problem Statement
Given a string s, find the length of the longest substring that contains no repeating characters.
Solution with Sliding Window
To solve this, we:
Breaking It Down
Expand the window by moving the right pointer across the string.
3.Handle Repeats:
If the character at right is already in char_set, move the left pointer to shrink the window until duplicates are removed.
领英推荐
4. Update the Result:
Track the maximum length of the window at each step.
Why Sliding Window is Efficient
def length_of_longest_substring(s: str) -> int:
char_set = set ()
left = 0
max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left +=1
char_set.add(s[right])
max_length=max(max_length,right-left+1)
return max_length
s="abcabcbb"
print(length_of_longest_substring(s))
Breaking It Down
Expand the window by moving the right pointer across the string.
3. Handle Repeats:
If the character at right is already in char_set, move the left pointer to shrink the window until duplicates are removed.
Why Sliding Window is Efficient
When to Use Sliding Window
Sliding window is ideal for problems like:
Conclusion
The sliding window with two pointers is a versatile and efficient tool for solving problems involving sequences. By maintaining a dynamic window and adjusting it based on conditions, you can solve complex challenges with clarity and efficiency.
Try applying this technique to other problems, such as:
Mastering this approach will make you more confident and capable of tackling real-world data challenges!
Software Engineer || Frappe Developer || Python ||JavaScript
2 个月Tackled a number on this sliding window algorithm. Thank for sharing this