POTD #22 - Longest substring with distinct characters | Geeks For Geeks
POTD #22 - Longest substring with distinct characters | Geeks For Geeks
{% raw %}
Problem Statement
Geeks For Geeks : https://www.geeksforgeeks.org/problems/longest-distinct-characters-in-string5848/1
Given a string s, find the length of the longest substring with all distinct characters.
Input: s = "geeksforgeeks"Output: 7Explanation: "eksforg" is the longest substring with all distinct characters.
Input: s = "abcdefabcbb"Output: 6Explanation: The longest substring with all distinct characters is "abcdef", which has a length of 6.
My Approach – Sliding Window
class Solution: def longestUniqueSubstr(self, s): # code here 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 #crux char_index[char] = i max_length = max(max_length, i - start + 1) return max_length {% endraw %}
This post is licensed under CC BY 4.0 by the author.