Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python program to find the longest word in a sentence
Next article icon

Python Program To Find Length Of The Longest Substring Without Repeating Characters

Last Updated : 20 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  • For “ABDEFGABEF”, the longest substring are “BDEFGA” and "DEFGAB", with length 6.
  • For “BBBB” the longest substring is “B”, with length 1.
  • For "GEEKSFORGEEKS", there are two longest substrings shown in the below diagrams, with length 7

The desired time complexity is O(n) where n is the length of the string.

 

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. 
 

Method 1 (Simple : O(n3)): We can consider all substrings one by one and check for each substring whether it contains all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substring contains all unique characters or not can be checked in linear time by scanning it from left to right and keeping a map of visited characters. Time complexity of this solution would be O(n^3).

Python3
# Python3 program to find the length # of the longest substring without # repeating characters  # This functionr eturns true if all # characters in strr[i..j] are  # distinct, otherwise returns false def areDistinct(strr, i, j):      # Note : Default values in visited are false     visited = [0] * (26)      for k in range(i, j + 1):         if (visited[ord(strr[k]) -                     ord('a')] == True):             return False                      visited[ord(strr[k]) -                 ord('a')] = True      return True  # Returns length of the longest substring # with all distinct characters. def longestUniqueSubsttr(strr):          n = len(strr)          # Result     res = 0           for i in range(n):         for j in range(i, n):             if (areDistinct(strr, i, j)):                 res = max(res, j - i + 1)                      return res  # Driver code if __name__ == '__main__':          strr = "geeksforgeeks"     print("The input is ", strr)          len = longestUniqueSubsttr(strr)     print("The length of the longest "           "non-repeating character substring is ", len)  # This code is contributed by mohit kumar 29 

Output
The input string is geeksforgeeks  The length of the longest non-repeating character substring is 7

Method 2 (Better : O(n2)) The idea is to use window sliding. Whenever we see repetition, we remove the previous occurrence and slide the window.

Python3
# Python3 program to find the  # length of the longest substring # without repeating characters def longestUniqueSubsttr(str):          n = len(str)          # Result     res = 0        for i in range(n):                   # Note : Default values in          # visited are false         visited = [0] * 256              for j in range(i, n):               # If current character is visited             # Break the loop             if (visited[ord(str[j])] == True):                 break               # Else update the result if             # this window is larger, and mark             # current character as visited.             else:                 res = max(res, j - i + 1)                 visited[ord(str[j])] = True                      # Remove the first character of previous         # window         visited[ord(str[i])] = False          return res  # Driver code str = "geeksforgeeks" print("The input is ", str)  len = longestUniqueSubsttr(str) print("The length of the longest "        "non-repeating character substring is ", len)  # This code is contributed by sanjoy_62 

Output
The input string is geeksforgeeks  The length of the longest non-repeating character substring is 7

Method 4 (Linear Time): Let us talk about the linear time solution now. This solution uses extra space to store the last indexes of already visited characters. The idea is to scan the string from left to right, keep track of the maximum length Non-Repeating Character Substring seen so far in res. When we traverse the string, to know the length of current window we need two indexes. 
1) Ending index ( j ) : We consider current index as ending index. 
2) Starting index ( i ) : It is same as previous window if current character was not present in the previous window. To check if the current character was present in the previous window or not, we store last index of every character in an array lasIndex[]. If lastIndex[str[j]] + 1 is more than previous start, then we updated the start index i. Else we keep same i.  

Below is the implementation of the above approach :

Python3
# Python3 program to find the length # of the longest substring # without repeating characters def longestUniqueSubsttr(string):      # last index of every character     last_idx = {}     max_len = 0      # starting index of current      # window to calculate max_len     start_idx = 0      for i in range(0, len(string)):                # Find the last index of str[i]         # Update start_idx (starting index of current window)         # as maximum of current value of start_idx and last         # index plus 1         if string[i] in last_idx:             start_idx = max(start_idx, last_idx[string[i]] + 1)          # Update result if we get a larger window         max_len = max(max_len, i-start_idx + 1)          # Update last index of current char.         last_idx[string[i]] = i      return max_len   # Driver program to test the above function string = "geeksforgeeks" print("The input string is " + string) length = longestUniqueSubsttr(string) print("The length of the longest non-repeating character" +       " substring is " + str(length)) 

Output
The input string is geeksforgeeks  The length of the longest non-repeating character substring is 7

Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26. 
Auxiliary Space: O(d) 

Alternate Implementation : 

Python
# Here, we are planning to implement a simple sliding window methodology   def longestUniqueSubsttr(string):           # Creating a set to store the last positions of occurrence     seen = {}     maximum_length = 0       # starting the initial point of window to index 0     start = 0            for end in range(len(string)):           # Checking if we have already seen the element or not         if string[end] in seen:              # If we have seen the number, move the start pointer             # to position after the last occurrence             start = max(start, seen[string[end]] + 1)           # Updating the last seen value of the character         seen[string[end]] = end         maximum_length = max(maximum_length, end-start + 1)     return maximum_length   # Driver Code string = "geeksforgeeks" print("The input string is", string) length = longestUniqueSubsttr(string) print("The length of the longest non-repeating character substring is", length) 

Output
The input String is geeksforgeeks  The length of the longest non-repeating character substring is 7

As an exercise, try the modified version of the above problem where you need to print the maximum length NRCS also (the above program only prints the length of it).

Please refer complete article on Length of the longest substring without repeating characters for more details!

Next Article
Python program to find the longest word in a sentence
author
kartik
Improve
Article Tags :
  • Strings
  • Python Programs
  • DSA
  • Microsoft
  • Amazon
  • Morgan Stanley
  • Housing.com
Practice Tags :
  • Amazon
  • Housing.com
  • Microsoft
  • Morgan Stanley
  • Strings

Similar Reads

  • Python program to repeat M characters of a string N times
    In this article, the task is to write a Python program to repeat M characters of string N times. Method 1: Define a function that will take a word, m, and n values as arguments.If M is greater than the length of the word. Set m value equal to the length of the wordNow store the characters needed to
    3 min read
  • Python program to find the longest word in a sentence
    In this article, we will explore various methods to find the longest word in a sentence. Using LoopFirst split the sentence into words using split() and then uses a loop (for loop) to iterate through the words and keeps track of the longest word by comparing their lengths. [GFGTABS] Python s =
    1 min read
  • Python program to remove the nth index character from a non-empty string
    Given a String, the task is to write a Python program to remove the nth index character from a non-empty string Examples: Input: str = "Stable" Output: Modified string after removing 4 th character Stabe Input: str = "Arrow" Output: Modified string after removing 4 th character Arro The first approa
    4 min read
  • Python Program to get number of consecutive repeated substring
    Given a substring K, the task is to write a Python Program to find the repetition of K string in each consecutive occurrence of K. Example Input : test_str = 'geeksgeeks are geeksgeeksgeeks for all geeks', K = "geeks" Output : [2, 3, 1] Explanation : First consecution of 'geeks' is 2. Input : test_s
    4 min read
  • Python program to remove last N characters from a string
    In this article, we’ll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions. Using String SlicingString slicing is one of the simplest and mo
    2 min read
  • Python | Longest Run of given Character in String
    Sometimes, while working with Strings, we can have a problem in which we need to perform the extraction of length of longest consecution of certain letter. This can have application in web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method
    6 min read
  • Python program to calculate the number of words and characters in the string
    We are given a string we need to find the total number of words and total number of character in the given string. For Example we are given a string s = "Geeksforgeeks is best Computer Science Portal" we need to count the total words in the given string and the total characters in the given string.
    3 min read
  • Python Program to find the Larger String without Using Built-in Functions
    Given two strings. The task is to find the larger string without using built-in functions. Examples: Input: GeeksforGeeks Geeks Output: GeeksforGeeks Input: GeeksForFeeks is an good Computer Coding Website It offers several topics Output: GeeksForFeeks is an good Computer Coding Website Step-by-step
    3 min read
  • Python3 Program to Minimize characters to be changed to make the left and right rotation of a string same
    Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc
    3 min read
  • Python Program to Return the Length of the Longest Word from the List of Words
    When working with lists of words in Python, we may need to determine the length of the longest word in the list. For example, given a list like ["Python", "with", "GFG], we would want to find that "Python" has the longest length. Let's go through some methods to achieve this. Using max() max() funct
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences