Longest substring with at most 2 distinct characters I think I solved the following problem. However, I was wondering if there was a faster or more efficient way to solve this.

I believe the the runtime is O(n) and space is O(1)  (O(256) assuming ASCII)

# Longest substring with at most 2 distinct characters
#
# Given a string S, find the length of the longest substring T that contains at most 2 distinct characters
#
# For example,
#     Given S = "eceba"
#     T is "ece" which it's length is 3

def longest_substring(string):
    if string is None or len(string) == 1 or len(string) == 0:
        return 0
    distinct_set = set()
    longest = 0
    current = 0
    for i in string:
        set_len = len(distinct_set)
        if set_len &lt; 2:
            if i in distinct_set:
                current += 1
            if i not in distinct_set:
                distinct_set.add(i)
                current += 1
        if set_len == 2:
            if i in distinct_set:
                current += 1
            if i not in distinct_set:
                distinct_set.clear()
                distinct_set.add(i)
                if current &gt; longest:
                    longest = current
                current = 1
        if current &gt; longest:
            longest = current
    return longest


Input:

test_cases = [None, "", "a", "ab", "aab", "bab", "babc", "bbbbcccac"]


Output:

0, 0, 0, 2, 3, 3, 3, 7
Three small things:

Firstly, docstrings exist. Use them. Put the explanation for how to use your method in them. That means that instead of this:

# Longest substring with at most 2 distinct characters
#
# Given a string S, find the length of the longest substring T that contains at most 2 distinct characters
#
# For example,
#     Given S = "eceba"
#     T is "ece" which it's length is 3

def longest_substring(string):


you have this:

def longest_substring(string):
    """ Longest substring with at most 2 distinct characters
    Given a string S, find the length of the longest substring T that contains t most 2 distinct characters
    For example,
        Given S = "eceba"
        T is "ece" which it's length is 3"""


At least, if I've understood their purpose correctly. 

Secondly, if someone passes in None, that should probably be an error, not a return 0 case. Same if someone passes in a number, Duck, or any other invalid type.

Thirdly, according to PEP8, the official style guide, none of your lines should be longer than 80 characters. The (new) second line violates this; it even did before. Just split it in half and you're good.