3 Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given"abcabcbb", the answer is"abc", which the length is 3.

Given"bbbbb", the answer is"b", with the length of 1.

Given"pwwkew", the answer is"wke", with the length of 3. Note that the answer must be asubstring,"pwke"is asubsequence and not a substring.

The Idea: The basic idea is to maintain two pointers. One left, and one right, both of which begin at 0. These left and right pointers are going maintain the current substring and hence also represent their length. Additionally, use a hash table to store the previous instance of a character. Move forward with the right iterator until we encounter a duplicate character (which can be identified through the hash table). When we encounter a a duplicate, move the left pointer so that we have no duplicates. We can use the hash table to identify where that previous duplicate character was. Moving the left point + 1 past this position will may ensure that the substring does not have any duplicates. The is one more thing. Consider the string abba. When we encounter the last a, our left pointer will point to index 1 since character a was duplicated. However, because we have moved the left pointer to index 2 after first having identified the duplicate of b, the first is become irrelevant. In other words, the left pointer can only move forwards in order to account for old history changes.

.   .
a b c a b c b b
  .   .
a b c a b c b b
    .   .
a b c a b c b b
      .   .
a b c a b c b b
          .   .
a b c a b c b b

Complexity: O(n) time and space.

int lengthOfLongestSubstring(string s) {

    unordered_map<char, int> d;
    int max_ = 0;

    int l = 0;
    for (int r = 0; r < s.size(); r++) {
        char c = s[r];
        // adjust left so we dont have a conflict
        if (d.find(c) != d.end()) {
            l = max(d[c] + 1, l);
        }

        // update most latest position
        d[c] = r;

        // length substr = l - r + 1
        max_ = max(max_, r - l + 1);
    }

    return max_;
}

Python

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0

        prev_char = {}
        left = 0
        max_length = -1

        for right, cur_char in enumerate(s):
            if cur_char in prev_char:
                left = max(prev_char[cur_char] + 1, left)
            prev_char[cur_char] = right
            max_length = max(max_length, right - left + 1)
        return max_length


obj = Solution()
print(obj.lengthOfLongestSubstring("abba"))

Last updated