Given a string s, write a Python function to find the length of the longest substring without repeating characters.
💡 Model Answer
The classic solution uses a sliding‑window technique with a hash map (or dictionary) to track the last index of each character. Initialize two pointers, left and right, both at 0, and an empty dictionary. Iterate right over the string. For each character s[right], if it has been seen and its last index is >= left, move left to last_index + 1 to shrink the window and remove repeating characters. Update the dictionary with the current index of s[right]. The window size is right - left + 1; keep a variable max_len to store the maximum window size seen. After the loop, return max_len. This algorithm runs in O(n) time because each character is processed at most twice (once by right, once by left) and uses O(min(n, alphabet_size)) space for the dictionary. Example: for "abcabcbb" the function returns 3 for substring "abc". The code is concise and handles edge cases such as empty strings or all identical characters.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500