O(n) time O(1) space solution using Kadane's algo in Java
Idea is that, while we traverse form left to right if we see a character at position j is a duplicate of a character at a position i < j on the left then we kno
Idea is that, while we traverse form left to right if we see a character at position j is a duplicate of a character at a position i < j on the left then we know that we can't start the substring from i anymore. So, we need to start a new substring from i+1 position. While doing this we also need to update the length of current substring and start of current substring. Important part of this process is to make sure that we always keep the latest position of the characters we have seen so far. Below is a simple O(n) implementation of this logic.\n\n\n    public class Solution {\n        public int lengthOfLongestSubstring(String s) {\n            int lastIndices[] = new int[256];\n            for(int i = 0; i<256; i++){\n                lastIndices[i] = -1;\n            }\n            \n            int maxLen = 0;\n            int curLen = 0;\n            int start = 0;\n            int bestStart = 0;\n            for(int i = 0; i<s.length(); i++){\n                char cur = s.charAt(i);\n                if(lastIndices[cur]  < start){\n                    lastIndices[cur] = i;\n                    curLen++;\n                }\n                else{\n                    int lastIndex = lastIndices[cur];\n                    start = lastIndex+1;\n                    curLen = i-start+1;\n                    lastIndices[cur] = i;\n                }\n                \n                if(curLen > maxLen){\n                    maxLen = curLen;\n                    bestStart = start;\n                }\n            }\n            \n            return maxLen;\n        }\n    }
[]