Python Easy 2 approaches ✅
Sliding Window - Counter\n\nThis approach uses counter variable to track number of characters in a sliding window. Whenever we encounter a state where the windo
1. ## **Sliding Window - Counter**\n\nThis approach uses `counter` variable to track number of characters in a sliding window. Whenever we encounter a state where the window becomes invalid due to number of characters(count of any character > 1), we would update the left bound of the new valid window.\n\n```\nclass Solution:\n    def lengthOfLongestSubstring(self, s: str) -> int:\n        counter = defaultdict(int)        # track counts of each character\n        l=0\n        max_length=0\n        for r, c in enumerate(s):\n            counter[c]+=1            \n            if counter[c] > 1:                \n                while l<r and counter[c]>1: # iterate until window is valid\n                    counter[s[l]]-=1\n                    l+=1\n            max_length=max(max_length, r-l+1)\n        return max_length\n```\n**Time  - O(2n)** - Iterates both `l` and `r` once through the input `s`.\n**Space - O(n)**\n\n---\n\n2. ## **Sliding Window - Last Seen**\n\nIf we observe the previous approach, we would notice we don\'t need to track the counts of each character in a sliding window. We just need to track the last seen of a character. This will help us figure out whether a character exists in the current sliding window.\n\n```\nclass Solution:\n    def lengthOfLongestSubstring(self, s: str) -> int:\n        last_seen = {}\n        l=0\n        max_length=0\n        for r in range(len(s)):\n            if s[r] in last_seen:\n                l=max(last_seen[s[r]], l)\n            \n            last_seen[s[r]]=r+1\n            max_length=max(max_length, r-l+1)\n        return max_length\n                    \n```\n\n**Time  - O(n)** - Iterates both `l` and `r` once through the input `s`.\n**Space - O(n)**\n\n\n---\n\n***Please upvote if you find it useful***
['Python', 'Python3']