Weekly Coding Challenge: Longest Substring Without Repeating Characters – written in Python

Posted by

Hello readers! It’s really important for me to continue my practice and learning. Every week, I block off 30 minutes, set a timer and choose a challenge from leetcode. This helps me keep my skills sharp, see how other devs all over the planet would solve these problems, and take some leisure time to problem solve and be creative. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. Today, the problem set focuses on Python.

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

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        
        substring = [] #initialize substring array to empty
        longest = 0 #set longest value to 0
        
        for i in s:
            if (i not in substring): # check if letter in s is in substring, if not, then...
                substring.append(i) # add the letter to the substring array
                if (len(substring) > longest): #continously check to see if substring is greater than longest
                    longest = len(substring) #if it is, update longest to the new value
            else: #if i is in substring, it means we have found a duplicate
                substring = substring[substring.index(i)+1:] #get everything to the right of the original dupe
                substring.append(i) #we still want to add the letter to the substring        
        return longest #return the longest int value

All solutions are also now on my GitHub profile if you want to check out all of the coding challenges I’ve completed so far!

All credit to problem sets goes to Leetcode

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s