Longest Substring Without Repeating Characters (Sliding Window)
Given a string s, find the length of the longest substring without duplicate characters. Frequently tested in TCS Prime & Digital technical rounds.
def length_of_longest_substring(s: str) -> int:
char_index_map = {}
max_length = 0
start = 0
for end, char in enumerate(s):
# If character was seen inside the current window, move start pointer
if char in char_index_map and char_index_map[char] >= start:
start = char_index_map[char] + 1
char_index_map[char] = end
max_length = max(max_length, end - start + 1)
return max_length
# Test Verification:
# s = "abcabcbb" -> 3 ("abc")
# s = "bbbbb" -> 1 ("b")
# s = "pwwkew" -> 3 ("wke")