## Description

https://leetcode.com/problems/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 a *subsequence* and not a substring.

## Explanation

We use two pointers technique to solve the problem. One slow pointer **i**, one fast pointer **j**.

We also add a HashSet to store the characters which have been visited by **j** pointer to help detect repeating characters.

We keep moving **j** pointer right further.

- If current
**s.charAt(j)**character is not in the HashSet, we add the character to the HashSet and keep moving**j**further. - If current
**s.charAt(j)**character is in the HashSet, we remove the character i is visiting and move**i**forward. At this point, we found the maximum size of substrings without duplicate characters start with index**i**. We move**i**pointer one step further.

When **j **pointer iterates all the characters of the string, we get the max length of the longest substring without repeating characters.

## Video Tutorial

## Java Solution

class Solution { public int lengthOfLongestSubstring(String s) { int maxLength = 0; HashSet<Character> set = new HashSet<>(); int i = 0; int j = 0; while (j < s.length()) { if (!set.contains(s.charAt(j))) { set.add(s.charAt(j)); j++; maxLength = Math.max(maxLength, j - i); } else { set.remove(s.charAt(i)); i++; } } return maxLength; } }

Hello There,

If we consider this use-case, “abcddefghijal” – for this string, shouldn’t the output be 6 and not 9? i.e. (efghij) and not (defghijal) as d and a are repeating. Please correct me if I am wrong. Thanks.

This is incorrect

sorry, the solution is correct… i overlooked

lol, np.. thank you for visiting 🙂

Your answer is incorrect. What is the output for “abcabcbb” ?

The output for “abcabcbb” is 3. It is the correct answer. Which part you think is incorrect?

Print hashset before u return and it is showing wrong result.