{"id":10582,"date":"2026-11-29T06:32:22","date_gmt":"2026-11-29T06:32:22","guid":{"rendered":"https:\/\/cybersecurityinfocus.com\/?p=10582"},"modified":"2026-11-29T06:32:22","modified_gmt":"2026-11-29T06:32:22","slug":"longest-substring-without-repeating-characters-sliding-window-explained","status":"publish","type":"post","link":"https:\/\/cybersecurityinfocus.com\/?p=10582","title":{"rendered":"Longest Substring Without Repeating Characters: Sliding Window Explained"},"content":{"rendered":"<p class=\"wp-block-paragraph\"><strong>Medium \u00b7 Sliding window \u00b7 Python.<\/strong> Prerequisites: strings, hash maps and loops.<\/p>\n<p>The window expands, moves left on a duplicate, and finds a maximum length of 2.<\/p>\n<p class=\"wp-block-paragraph\">Imagine scanning a stream of characters to find the longest uninterrupted segment without duplicates. Restarting at every character wastes work. A sliding window remembers what is already valid.<\/p>\n<h2 class=\"wp-block-heading\">Problem and examples<\/h2>\n<p class=\"wp-block-paragraph\">Given a string s, return the length of its longest contiguous substring containing no repeated characters. A substring is contiguous; a subsequence need not be.<\/p>\n<p>InputOutputExample windowabcabcbb3abcbbbbb1bpwwkew3wkeabba2abempty string0empty<\/p>\n<h2 class=\"wp-block-heading\">Constraints and edge cases<\/h2>\n<p class=\"wp-block-paragraph\">Allow an empty string, repeated characters, spaces and Unicode code points. For large inputs, quadratic work becomes expensive; aim for a single pass. A substring must remain contiguous.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Pattern recognition:<\/strong> When a problem asks for the longest contiguous segment satisfying a condition, consider a variable-length sliding window. Here, adding a character can violate uniqueness, and removing characters from the left restores it.<\/p>\n<h2 class=\"wp-block-heading\">Brute force<\/h2>\n<p class=\"wp-block-paragraph\">Start at every index, extend a set until a duplicate appears, and track the maximum. Worst-case time O(n\u00b2), auxiliary space O(min(n, alphabet size)).<\/p>\n<p>def brute(s):<br \/>\n    best = 0<br \/>\n    for i in range(len(s)):<br \/>\n        seen = set()<br \/>\n        for j in range(i, len(s)):<br \/>\n            ch = s[j]<br \/>\n            if ch in seen:<br \/>\n                break<br \/>\n            seen.add(ch)<br \/>\n            best = max(best, len(seen))<br \/>\n    return best<\/p>\n<p class=\"wp-block-paragraph\">The brute-force method repeatedly examines overlapping windows. For example, after examining abc in abcabcbb, starting again at b repeats work. Instead, retain the valid suffix and discard only the prefix that causes a duplicate.<\/p>\n<h2 class=\"wp-block-heading\">Optimize using a sliding window<\/h2>\n<p>Maintain left and right boundaries of a duplicate-free window.Store the latest index of each character.When a duplicate lies inside the window, jump left beyond its previous occurrence.Update the best length after restoring the invariant.<\/p>\n<h2 class=\"wp-block-heading\">Visual walkthrough<\/h2>\n<p>Index:     0  1  2  3<br \/>\nString:    a  b  b  a<\/p>\n<p>Step 1:   [a] b  b  a    best = 1<br \/>\nStep 2:   [a  b] b  a    best = 2<br \/>\nStep 3:    a  b [b] a    best = 2<br \/>\nStep 4:    a  b [b  a]   best = 2<\/p>\n<p class=\"wp-block-paragraph\">The brackets show the valid window after each character is processed. At step 3, the repeated b forces left to jump to index 2. At step 4, the old a is outside the window, so left stays at 2.<\/p>\n<h2 class=\"wp-block-heading\">Dry run: abba<\/h2>\n<p>RightCharacterLeftWindowBest0a0a11b0ab22b2b23a2ba2<\/p>\n<p class=\"wp-block-paragraph\">The last a was at index 0, outside the current window. Never move left backward. This is the most common bug.<\/p>\n<h2 class=\"wp-block-heading\">Python solution<\/h2>\n<p>def longest_unique(s: str) -&gt; int:<br \/>\n    last = {}<br \/>\n    left = best = 0<br \/>\n    for right, ch in enumerate(s):<br \/>\n        left = max(left, last.get(ch, -1) + 1)<br \/>\n        last[ch] = right<br \/>\n        best = max(best, right &#8211; left + 1)<br \/>\n    return best<\/p>\n<p>assert longest_unique(&#8216;abba&#8217;) == 2<br \/>\nassert longest_unique(&#8221;) == 0<br \/>\nassert longest_unique(&#8216;pwwkew&#8217;) == 3<\/p>\n<h2 class=\"wp-block-heading\">Complexity and correctness<\/h2>\n<p class=\"wp-block-paragraph\">Expected O(n) time with hash maps. Python uses O(min(n, alphabet size)) map space. The invariant is that the current window contains no duplicate. Moving left beyond the previous occurrence restores it while preserving the longest valid suffix ending at right.<\/p>\n<p>ApproachTimeAuxiliary spaceBrute forceO(n\u00b2)O(min(n, alphabet size))Sliding windowExpected O(n)O(min(n, alphabet size))<\/p>\n<h2 class=\"wp-block-heading\">Common mistakes<\/h2>\n<p class=\"wp-block-paragraph\">Do not move left backward when a previous occurrence is outside the window. Update the last occurrence only after using its old value. Compute the inclusive length as right minus left plus one. Initialize best to zero to handle empty input.<\/p>\n<h2 class=\"wp-block-heading\">Interview practice<\/h2>\n<p>Why use max(left, previous + 1)?<\/p>\n<p class=\"wp-block-paragraph\">A previous occurrence may be outside the active window. Taking the maximum prevents the left boundary from moving backward and reintroducing duplicates.<\/p>\n<p>Why not sort the string?<\/p>\n<p class=\"wp-block-paragraph\">Sorting changes character order and destroys the contiguous substring property.<\/p>\n<p>Why is the algorithm linear?<\/p>\n<p class=\"wp-block-paragraph\">The right pointer visits each character once and the left pointer only moves forward. Hash map operations take expected constant time.<\/p>\n<p>What is the window invariant?<\/p>\n<p class=\"wp-block-paragraph\">After adjusting left, every character in the active window is unique. It is the longest valid suffix ending at right.<\/p>\n<h2 class=\"wp-block-heading\">Related problem variations<\/h2>\n<p class=\"wp-block-paragraph\">Try these independently: return the longest unique substring itself; longest substring with at most K distinct characters; minimum window substring; longest repeating character replacement; process an incoming character stream.<\/p>\n<h2 class=\"wp-block-heading\">Try it yourself<\/h2>\n<p class=\"wp-block-paragraph\">Trace dvdf by hand before running the code. Then test all-identical strings, all-distinct strings and strings containing spaces. Compare against the brute force implementation on randomly generated short strings.<\/p>\n<h2 class=\"wp-block-heading\">Quick revision<\/h2>\n<p class=\"wp-block-paragraph\">Variable-length sliding window: expand right, restore validity, update answer. Never move left backward. Practice the original problem at <a href=\"https:\/\/leetcode.com\/problems\/longest-substring-without-repeating-characters\/\" target=\"_blank\" rel=\"noopener\">LeetCode<\/a>.<\/p>","protected":false},"excerpt":{"rendered":"<p>Medium \u00b7 Sliding window \u00b7 Python. Prerequisites: strings, hash maps and loops. The window expands, moves left on a duplicate, and finds a maximum length of 2. Imagine scanning a stream of characters to find the longest uninterrupted segment without duplicates. Restarting at every character wastes work. A sliding window remembers what is already valid. [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":10583,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-10582","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10582"}],"collection":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10582"}],"version-history":[{"count":0,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10582\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/media\/10583"}],"wp:attachment":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10582"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10582"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10582"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}