# 3. Longest Substring Without Repeating Characters

{% embed url="<https://leetcode.com/problems/longest-substring-without-repeating-characters/description/>" %}

### better

> Time: O(n)

> space: O(1), number of unique characters limited

```jsx
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {

    if (s.length < 2) return s.length;
    
    const memo = {};
    
    let max = 0;
    let left = 0;
    for (let i = 0; i < s.length; i++) {
        curr = s.charAt(i);
        if (memo[curr] !== undefined) {
            left = Math.max(memo[curr] + 1, left);
        }
        max = Math.max(max, i - left + 1);
        memo[curr] = i;
    }

    return max;
};
```

### Brute force

> time: O(n^2)

> time: O(n)

```jsx
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    s = [...s];
    // empty? length 1?
    if (s.length < 2) return s.length;
    
    let max = 0;
    for (let i = 0; i < s.length; i++) {
        const set = new Set([s[i]]);
        for (let j = i + 1; j < s.length; j++) {
            const curr = s[j];
            if (set.has(curr)) {
                break;
            } else {
                set.add(curr);
            }
        }
        max = Math.max(max, set.size);
    }

    return max;
};
```


---

# 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://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/string/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.
