0% found this document useful (0 votes)
2 views1 page

Optimal Code

The provided Python code defines a class 'Solution' with a method 'lengthOfLongestSubstring' that calculates the length of the longest substring without repeating characters in a given string. It utilizes a sliding window approach with a set to track unique characters, ensuring an efficient O(n) time complexity and O(min(m,n)) space complexity. The method iterates through the string, adjusting the left pointer to maintain the uniqueness of characters in the current substring.

Uploaded by

sarthak kelkar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

Optimal Code

The provided Python code defines a class 'Solution' with a method 'lengthOfLongestSubstring' that calculates the length of the longest substring without repeating characters in a given string. It utilizes a sliding window approach with a set to track unique characters, ensuring an efficient O(n) time complexity and O(min(m,n)) space complexity. The method iterates through the string, adjusting the left pointer to maintain the uniqueness of characters in the current substring.

Uploaded by

sarthak kelkar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Code: Longest Substring Without Repeating

Characters
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
char_set = set()
left = 0
max_len = 0

for right in range(len(s)):


while s[right] in char_set:
char_set.remove(s[left])
left += 1

char_set.add(s[right])
max_len = max(max_len, right - left + 1)

return max_len

# O(n) : tc
# O(min(m,n)) : sc

You might also like