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

# Longest Substring Without Repeating Characters

Given a string, find the longest substring without any repeating characters and return the length of it. The input string is guaranteed to be not null.

For example, the longest substring without repeating letters for "bcdfbd" is "bcdf", we should return 4 in this case.

**High level**

hashTable to track chars seen and their last seen index

for each char in string

if not in HT:

&#x20;curmax += 1&#x20;

update globalmax&#x20;

add char, index into HT

if is in HT:

&#x20;get index of char&#x20;

curmax = current index - index of repeated char

&#x20;for 0 to index of repeated char: HT.remove(String.charAt(i))

```
public class Solution {
  public int longest(String input) {

    Map<Character, Integer> ht = new HashMap<>();
    int globalMax = 0;
    int curMax = 0;
    for (int i = 0; i < input.length(); i++){
      Character cur = input.charAt(i);
      if (!ht.containsKey(cur)){
        curMax += 1;
        globalMax = Math.max(globalMax, curMax);
        ht.put(cur, i);
      } else {
        int prevIndex = ht.get(cur);
        int left = i - curMax; //left end of cur substring
        while(left <= prevIndex){
          Character removeChar = input.charAt(left);
          ht.remove(removeChar);
          left += 1;
        }
        ht.put(cur, i);
        curMax = i - prevIndex;
      }
    }

    return globalMax;
  }
}

```
