# 3 Longest Substring Without Repeating Characters

Given a string, find the length of the **longest substring** without repeating characters.

**Examples:**

Given`"abcabcbb"`, the answer is`"abc"`, which the length is 3.

Given`"bbbbb"`, the answer is`"b"`, with the length of 1.

Given`"pwwkew"`, the answer is`"wke"`, with the length of 3. Note that the answer must be a**substring**,`"pwke"`is asubsequence and not a substring.

**The Idea:** The basic idea is to maintain two pointers. One left, and one right, both of which begin at 0. These left and right pointers are going maintain the current substring and hence also represent their length. Additionally, use a hash table to store the previous instance of a character. Move forward with the right iterator until we encounter a duplicate character (which can be identified through the hash table). When we encounter a a duplicate, move the left pointer so that we have no duplicates. We can use the hash table to identify where that previous duplicate character was. Moving the left point + 1 past this position will may ensure that the substring does not have any duplicates. The is one more thing. Consider the string `abba`. When we encounter the last a, our left pointer will point to index 1 since character a was duplicated. However, because we have moved the left pointer to index 2 after first having identified the duplicate of b, the first is become irrelevant. In other words, the left pointer can only move forwards in order to account for old history changes.

```
.   .
a b c a b c b b
  .   .
a b c a b c b b
    .   .
a b c a b c b b
      .   .
a b c a b c b b
          .   .
a b c a b c b b
```

**Complexity:** O(n) time and space.

```cpp
int lengthOfLongestSubstring(string s) {

    unordered_map<char, int> d;
    int max_ = 0;

    int l = 0;
    for (int r = 0; r < s.size(); r++) {
        char c = s[r];
        // adjust left so we dont have a conflict
        if (d.find(c) != d.end()) {
            l = max(d[c] + 1, l);
        }

        // update most latest position
        d[c] = r;

        // length substr = l - r + 1
        max_ = max(max_, r - l + 1);
    }

    return max_;
}
```

**Python**

```python
class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0

        prev_char = {}
        left = 0
        max_length = -1

        for right, cur_char in enumerate(s):
            if cur_char in prev_char:
                left = max(prev_char[cur_char] + 1, left)
            prev_char[cur_char] = right
            max_length = max(max_length, right - left + 1)
        return max_length


obj = Solution()
print(obj.lengthOfLongestSubstring("abba"))
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/3-longest-substring-without-repeating-characters.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
