Longest Substring Without Repeating Characters
Longest Substring Without Repeating Characters
Problem Statement
Given a string, find the length of the longest substring without repeating characters.
Video Explanation

Approach
We can use the sliding window technique along with a hash map to track the characters and their indices.
Steps:
-
Initialize:
- Create a hash map to store the last seen index of each character.
- Initialize two pointers,
startandend, to the beginning of the string.
-
Iterate:
- For each character, check if it has been seen and is in the current window.
- Update the
startpointer if necessary. - Update the
end.
-
Return:
- Return the maximum length found.
Solutions
- C++
- Java
- Python
- JavaScript
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> charMap;
int left = 0, maxLen = 0;
for (int right = 0; right < s.length(); right++) {
if (charMap.count(s[right]) && charMap[s[right]] >= left) {
left = charMap[s[right]] + 1;
}
charMap[s[right]] = right;
maxLen = max(maxLen, right - left + 1);
}
return maxLen;
}
};
import java.util.HashMap;
import java.util.Map;
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int left = 0, maxLen = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (map.containsKey(c) && map.get(c) >= left) {
left = map.get(c) + 1;
}
map.put(c, right);
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
}
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
char_index = {}
max_length = 0
start = 0
for i, char in enumerate(s):
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1
char_index[char] = i
max_length = max(max_length, i - start + 1)
return max_length
var lengthOfLongestSubstring = function(s) {
const map = new Map();
let left = 0, maxLen = 0;
for (let right = 0; right < s.length; right++) {
const c = s.charAt(right);
if (map.has(c) && map.get(c) >= left) {
left = map.get(c) + 1;
}
map.set(c, right);
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
};
Track Your Progress
Done with this topic? Mark it as complete to track your progress.
💬 Discuss this page
Have a question or spot something confusing in "Longest Substring Without Repeating Characters"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.