> For the complete documentation index, see [llms.txt](https://feifeizheng.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://feifeizheng.gitbook.io/leetcode/string/3.-longest-substring-without-repeating-characters.md).

# 3. Longest Substring Without Repeating Characters

## Question

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

**Example 1:**

```
Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 
```

**Example 2:**

```
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
```

**Example 3:**

```
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
```

## Complexity

* Time complexity: O(n)
* Space complexity: O(1)

## Code&#x20;

```python
def lengthOfLongestSubstring(self, s: str) -> int:
    n = len(s)
    if n < 2: #no prepeating word when n < 2
        return n 
    res, tmp = "", "" #init result and tmp substring
    for i, c in enumerate(s):
        if c not in tmp: #simply add char if not include
            tmp += c
        else:
            idx = tmp.find(c) #find index of char in tmp
            tmp = tmp[idx+1:] + c
        res = tmp if len(tmp) > len(res) else res
    return len(res)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://feifeizheng.gitbook.io/leetcode/string/3.-longest-substring-without-repeating-characters.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
