Strings are data structures comprised of a sequence of characters, Much like arrays, strings allow for efficient access to individual characters via indexing, making them remarkably similar to arrays in how they can be manipulated and accessed. Given this similarity, a solid understanding of arrays is beneficial as many of the same techniques and operations can directly apply to strings as well.
This technique, as listed under arrays, utilizes a similar approach in string manipulation, so please refer back to that section if you need a fundamental overview of the sliding window concept. In the context of strings, the sliding window technique is particularly effective for solving problems that involve substrings, where the goal is to find or analyze substrings within a larger string based on specific criteria
Let’s go through this Example Problem: Longest Substring Without Repeating Characters
We are given a string s
. The task is to find the length of the longest substring without repeating characters.
left
to track the left boundary of the window.char_set
to keep track of the unique characters in the current window.max_length
to store the maximum length of a valid substring encountered.right
for the right boundary of the window:
char_set
(i.e., a duplicate is found):
char_set
and incrementing left
until the duplicate is removed.char_set
.max_length
to be the maximum of max_length
and the current window length (right - left + 1
).max_length
after traversing the entire string.def lengthOfLongestSubstring(s):
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
char_set
to track the unique characters in the current window.left
to 0 to represent the left boundary of the window and max_length
to 0 to keep track of the maximum length of valid substrings.