Visual Explanation | Sliding Window JAVA
Logic:\nThis difficulty in this question is finding out where to pick our next substring once we\'ve spotted a duplicate character. Using two pointers and a sli
### Logic:\nThis difficulty in this question is finding out where to pick our next substring once we\'ve spotted a duplicate character. Using two pointers and a sliding window, we can quite easily choose what substring we want to look at. In fact, finding the longest substring without repeating characters becomes even easier once you realise the following observation.\n\n**Key Observation:**\n> Once we\'ve landed on a character we\'ve seen before, we want to move the left pointer of our window to the index *after* the last occurrence of that character.\n\nPay attention to the following example with the input string `s = "babcadba"` to see this in action:\n\n![image](https://assets.leetcode.com/users/images/394b1faa-f48c-486a-b672-8ccd6f758e2e_1666482154.3857741.png)\n\nAs you can see, our `nextIndex[]` array functions as both a hashset and a way to keep track of indexes. In particular, our array is storing the index AFTER the last occurrence of any character. That way, our left pointer can move directly there. \n___\n### How does this work in code?\nTurns out characters can function as integers. As such, we can use the characters themselves to access values of our `nextIndex[]` array. We\'ll need an array that has range: [0, 128) as that covers all ASCII characters that could be used in this question. \n\nSince we\'re working with two pointers, we can quite conveniently find the length of our current window using `r - l + 1`. We can update this anytime it\'s larger than our current maximum.\n\nAwesome. Now we\'re ready to start coding!\n\n___\n### Code\nIf you have any questions, suggestions or improvements, feel free to let me know. Thanks for reading!\n```java\npublic int lengthOfLongestSubstring(String s) {\n\tint n = s.length(), longest = 0;\n\tint[] nextIndex = new int[128]; \n\n\tfor (int r=0, l=0; r<n; r++) {\n\t\tl = Math.max(nextIndex[s.charAt(r)], l); \n\t\tlongest = Math.max(longest, r - l + 1);\n\t\tnextIndex[s.charAt(r)] = r + 1;\n\t}\n\n\treturn longest;\n}\n```\n**Time Complexity:** `O(n)` where `n` is the length of the string.\n**Space Complexity:** `O(128)` for the `nextIndex` array.
['Sliding Window', 'Java']