{"id":8039,"date":"2025-07-19T17:27:17","date_gmt":"2025-07-19T11:57:17","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=8039"},"modified":"2025-07-19T17:33:52","modified_gmt":"2025-07-19T12:03:52","slug":"longestsubstringwithoutrepeat","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/longestsubstringwithoutrepeat\/","title":{"rendered":"Longest Substring Without Repeating Characters"},"content":{"rendered":"\n\n<!-- Longest -->\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style> \n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #f8c291;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2{\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n.wp_blog_explanation h5{\n  color: var(--primary);\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n.wp_blog_explanation code {\n  background: #f9cea6;\n  color: #2d2d2d;\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n}\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0,0,0,0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\"> \n    <h1 class=\"wp_blog_main-heading\"><\/h1>\n    <div class=\"wp_blog_explanation\">\n        <h2>Problem Statement:<\/h2>\n\n        <p>Given a string s, find the length of the <strong>longest<\/strong> substring without duplicate characters.\n        <\/p>\n\n                <h2>Examples:<\/h2>\n                <h5>Example 1:<\/h5>\n                <p><strong>Input:<\/strong> s = &#8220;abcabcbb&#8221;<\/p>\n                <p><strong>Output:<\/strong> 3<\/p>\n                <p>\n                  <strong>Explanation:<\/strong>\n                  The answer is &#8220;abc&#8221;, with the length of 3.\n                <\/p>\n\n                <h5>Example 2:<\/h5>\n                <p><strong>Input:<\/strong> s = &#8220;bbbbb&#8221;<\/p>\n                <p><strong>Output:<\/strong> 1<\/p>\n                <p><strong>Explanation:<\/strong> The answer is &#8220;b&#8221;, with the length of 1.<\/p>\n\n                <h5>Example 3:<\/h5>\n                <p><strong>Input:<\/strong> s = &#8220;pwwkew&#8221;<\/p>\n                <p><strong>Output:<\/strong> 3<\/p>\n                <p><strong>Explanation:<\/strong> The answer is &#8220;wke&#8221;, with the length of 3.<\/p>\n\n                <p>Notice that the answer must be a substring, &#8220;pwke&#8221; is a subsequence and not a substring.<\/p>\n\n                    <h2>Constraints:<\/h2>\n                    <ul>\n                      <li><code>0 <= s.length <= 5 * 10<sup>4<\/sup><\/code><\/li>\n                      <li><code>s<\/code> consists of English letters, digits, symbols and spaces.<\/li>\n                    <\/ul>\n\n                <h2>Approach<\/h2>\n                <ul>\n                    <p>Using <strong>two pointers<\/strong> i and j to form a sliding window that keeps track of the current substring without repeating characters.<\/p>\n                    <li>A hash map map stores the <strong>most recent index<\/strong> of each character.<\/li>\n                    <li>If we encounter a repeating character that&#8217;s <code>within the current window<\/code>, we move the start pointer i just after its last occurrence.<\/li>\n                    <li>At each step, we calculate the window size and update the maximum length <code>maxWS<\/code>.<\/li>\n                <\/ul>\n\n                <h2>Time Complexity:<\/h2>\n                <li>\n                  <p><strong>Time Complexity = O(n)<\/strong>\n                  <\/li>\n                <h2>Space Complexity:<\/h2>\n                <li>\n                  <p><strong>Space Complexity = O(n)<\/strong><\/p>\n                <\/li>\n\n<h2>Dry Run<\/h2> <div style=\"background: #f9f9f9; border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0;\"> <p><strong>Input:<\/strong> <code>s = \"abcabcbb\"<\/code><\/p> <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\">\nInitialize: i = 0, j = 0, map = {}, maxWS = 0\n\n\/\/ Iteration over j\nj = 0 \u2192 s[j] = 'a'\n\u2192 'a' not in map\n\u2192 map = { a: 0 }\n\u2192 currWS = 0 - 0 + 1 = 1\n\u2192 maxWS = max(0, 1) = 1\n\nj = 1 \u2192 s[j] = 'b'\n\u2192 'b' not in map\n\u2192 map = { a: 0, b: 1 }\n\u2192 currWS = 1 - 0 + 1 = 2\n\u2192 maxWS = max(1, 2) = 2\n\nj = 2 \u2192 s[j] = 'c'\n\u2192 'c' not in map\n\u2192 map = { a: 0, b: 1, c: 2 }\n\u2192 currWS = 2 - 0 + 1 = 3\n\u2192 maxWS = max(2, 3) = 3\n\nj = 3 \u2192 s[j] = 'a'\n\u2192 'a' in map and map['a'] = 0 \u2265 i\n\u2192 i = map['a'] + 1 = 1\n\u2192 map = { a: 3, b: 1, c: 2 }\n\u2192 currWS = 3 - 1 + 1 = 3\n\u2192 maxWS = max(3, 3) = 3\n\nj = 4 \u2192 s[j] = 'b'\n\u2192 'b' in map and map['b'] = 1 \u2265 i\n\u2192 i = map['b'] + 1 = 2\n\u2192 map = { a: 3, b: 4, c: 2 }\n\u2192 currWS = 4 - 2 + 1 = 3\n\u2192 maxWS = max(3, 3) = 3\n\nj = 5 \u2192 s[j] = 'c'\n\u2192 'c' in map and map['c'] = 2 \u2265 i\n\u2192 i = map['c'] + 1 = 3\n\u2192 map = { a: 3, b: 4, c: 5 }\n\u2192 currWS = 5 - 3 + 1 = 3\n\u2192 maxWS = max(3, 3) = 3\n\nj = 6 \u2192 s[j] = 'b'\n\u2192 'b' in map and map['b'] = 4 \u2265 i\n\u2192 i = map['b'] + 1 = 5\n\u2192 map = { a: 3, b: 6, c: 5 }\n\u2192 currWS = 6 - 5 + 1 = 2\n\u2192 maxWS = max(3, 2) = 3\n\nj = 7 \u2192 s[j] = 'b'\n\u2192 'b' in map and map['b'] = 6 \u2265 i\n\u2192 i = map['b'] + 1 = 7\n\u2192 map = { a: 3, b: 7, c: 5 }\n\u2192 currWS = 7 - 7 + 1 = 1\n\u2192 maxWS = max(3, 1) = 3\n\nFinal map = { a: 3, b: 7, c: 5 }\nFinal maxWS = 3\n<\/pre>\n\n<p><strong>Output:<\/strong> <code>Result: 3<\/code><\/p> <\/div>\n                \n        <h2>Visualisation:<\/h2>\n        <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-19-at-5.23.43\u202fPM.png\" alt=\"longest\" \/>\n    <\/div>\n\n    <div class=\"wp_blog_code-tabs-container\">\n        <div class=\"wp_blog_code-tabs-header\">\n            <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n        <\/div>\n\n        <!-- JavaScript -->\n        <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n            <pre><code class=\"language-javascript\">\nvar lengthOfLongestSubstring = function(s) {\n    let i = j = 0;\n    let map = {};\n    let maxWS = 0;\n\n    for(j=0; j<s.length; j++){\n        if(map[s[j]] != undefined &#038;&#038; map[s[j]] >= i){\n            i = map[s[j]] + 1;\n        }\n        map[s[j]] = j;\n        currWS = j - i + 1;\n        maxWS = Math.max(maxWS, currWS); \n    }\n    return maxWS;\n};\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- Python -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n            <pre><code class=\"language-python\">\ndef lengthOfLongestSubstring(s: str) -> int:\n    map = {}\n    maxWS = 0\n    i = 0\n    for j in range(len(s)):\n        if s[j] in map and map[s[j]] >= i:\n            i = map[s[j]] + 1\n        map[s[j]] = j\n        currWS = j - i + 1\n        maxWS = max(maxWS, currWS)\n    return maxWS\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- Java -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n            <pre><code class=\"language-java\">\nimport java.util.HashMap;\n\nclass Solution {\n    public int lengthOfLongestSubstring(String s) {\n        HashMap<Character, Integer> map = new HashMap<>();\n        int maxWS = 0;\n        int i = 0;\n        for (int j = 0; j < s.length(); j++) {\n            if (map.containsKey(s.charAt(j)) &#038;&#038; map.get(s.charAt(j)) >= i) {\n                i = map.get(s.charAt(j)) + 1;\n            }\n            map.put(s.charAt(j), j);\n            int currWS = j - i + 1;\n            maxWS = Math.max(maxWS, currWS);\n        }\n        return maxWS;\n    }\n}\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- C++ -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n            <pre><code class=\"language-cpp\">\n#include &lt;iostream&gt;\n#include &lt;unordered_map&gt;\nusing namespace std;\n\nint lengthOfLongestSubstring(string s) {\n    unordered_map<char, int> map;\n    int maxWS = 0, i = 0;\n\n    for (int j = 0; j < s.length(); j++) {\n        if (map.find(s[j]) != map.end() &#038;&#038; map[s[j]] >= i) {\n            i = map[s[j]] + 1;\n        }\n        map[s[j]] = j;\n        int currWS = j - i + 1;\n        maxWS = max(maxWS, currWS);\n    }\n    return maxWS;\n}\n    <\/code><\/pre>\n        <\/div>\n\n        <!-- C -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n            <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\nint lengthOfLongestSubstring(char* s) {\n    int lastIndex[256];\n    for (int i = 0; i < 256; i++) {\n        lastIndex[i] = -1;\n    }\n\n    int maxWS = 0, i = 0;\n    for (int j = 0; s[j] != '\\0'; j++) {\n        if (lastIndex[(unsigned char)s[j]] >= i) {\n            i = lastIndex[(unsigned char)s[j]] + 1;\n        }\n        lastIndex[(unsigned char)s[j]] = j;\n        int currWS = j - i + 1;\n        if (currWS > maxWS) {\n            maxWS = currWS;\n        }\n    }\n    return maxWS;\n}\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- C# -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n            <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n    public int LengthOfLongestSubstring(string s) {\n        Dictionary<char, int> map = new Dictionary<char, int>();\n        int maxWS = 0, i = 0;\n\n        for (int j = 0; j < s.Length; j++) {\n            if (map.ContainsKey(s[j]) &#038;&#038; map[s[j]] >= i) {\n                i = map[s[j]] + 1;\n            }\n            map[s[j]] = j;\n            int currWS = j - i + 1;\n            maxWS = Math.Max(maxWS, currWS);\n        }\n        return maxWS;\n    }\n}\n        <\/code><\/pre>\n        <\/div>\n    <\/div>\n<\/div>\n\n<script>\n    document.addEventListener(\"DOMContentLoaded\", () => {\n        const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n        const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n        buttons.forEach((button) => {\n            button.addEventListener(\"click\", () => {\n                const lang = button.getAttribute(\"data-lang\");\n\n                buttons.forEach((btn) => btn.classList.remove(\"active\"));\n                contents.forEach((content) =>\n                    content.classList.remove(\"active\")\n                );\n\n                button.classList.add(\"active\");\n                document\n                    .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n                    .classList.add(\"active\");\n            });\n        });\n    });\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: Given a string s, find the length of the longest substring without duplicate characters. Examples: Example 1: Input: s = &#8220;abcabcbb&#8221; Output: 3 Explanation: The answer is &#8220;abc&#8221;, with the length of 3. Example 2: Input: s = &#8220;bbbbb&#8221; Output: 1 Explanation: The answer is &#8220;b&#8221;, with the length of 1. Example 3:<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":{"0":"post-8039","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms","7":"category-c-c-plus-plus","8":"category-csharp","9":"category-cplusplus","10":"category-data-structures","11":"category-data-structures-and-algorithms","12":"category-dsa","13":"category-java","14":"category-javascript","15":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8039","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=8039"}],"version-history":[{"count":2,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8039\/revisions"}],"predecessor-version":[{"id":8043,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8039\/revisions\/8043"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=8039"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=8039"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=8039"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}