Python implementation of the "Longest Substring Without Repeating Characters" problem using the sliding window technique:
def longest_substring(s):
char_index_map = {} # Stores the index of characters
left = 0 # Left boundary of the sliding window
max_length = 0 # Maximum length found
for right in range(len(s)):
if s[right] in char_index_map:
left = max(left, char_index_map[s[right]] + 1) # Move left boundary
char_index_map[s[right]] = right # Update index of character
max_length = max(max_length, right - left + 1) # Update max length
return max_length
# Example usage:
s = "abcabcbb"
print(longest_substring(s)) # Output: 3
char_index_map
dictionary keeps track of the last index of each character to avoid unnecessary repetitions.๐ง : 2nd example:
Prompt
Given a string s
, find the length of the longest substring without repeating characters.
def length_of_longest_substring(s: str) -> int:
✅ What It's Testing:
Sliding Window Technique – Efficient string traversal.
Hashing/Data Structures – Using sets or dictionaries to track characters.
Edge Case Thinking – Empty strings, all identical characters, etc.
Time Complexity Awareness – Naive solutions may be O(n²); optimal is O(n).
๐ Time and Space Complexity:
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(min(n, m)), where m is the character set size.
No comments:
Post a Comment