Algorithm for Longest Substring Without Duplicates
The big picture pseudo-code algorithm for finding the longest substring without duplicates is provided here. We'll make the same assumption about the lastPos
array as mentioned previously (that it can be indexed by x
and lastPos[x]
holds the last found occurrence of x
in the input string).
The figure below shows the entire process for an example.

xxxxxxxxxx
22
Method: longestSubstring
Input: Input string str
​
1. Initialize all elements of lastPos to -1
2. startInd = 0
3. len = 0
4. max = 0
5. i = 0
6. For each character x in str at position i
{
a. if startInd <= lastPos[x]
i. startInd = lastPos[x]+1
ii. len = i-startInd + 1
iii. lastPos[x] = i
b. if startInd > lastPos[x]
i. lastPos[x] = i
ii. len++
iii. if (len>max) max = len
}
7. return max
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment