Java Program To Find Length Of The Longest Substring Without Repeating Characters
Last Updated :
20 Dec, 2021
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.
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).
Java
// Java program to find the length of the
// longest substring without repeating
// characters
import java.io.*;
import java.util.*;
class GFG{
// This function returns true if all characters in
// str[i..j] are distinct, otherwise returns false
public static Boolean areDistinct(String str,
int i, int j)
{
// Note : Default values in visited are false
boolean[] visited = new boolean[26];
for(int k = i; k <= j; k++)
{
if (visited[str.charAt(k) - 'a'] == true)
return false;
visited[str.charAt(k) - 'a'] = true;
}
return true;
}
// Returns length of the longest substring
// with all distinct characters.
public static int longestUniqueSubsttr(String str)
{
int n = str.length();
// Result
int res = 0;
for(int i = 0; i < n; i++)
for(int j = i; j < n; j++)
if (areDistinct(str, i, j))
res = Math.max(res, j - i + 1);
return res;
}
// Driver code
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.println("The input string is " + str);
int len = longestUniqueSubsttr(str);
System.out.println("The length of the longest " +
"non-repeating character " +
"substring is " + len);
}
}
// This code is contributed by akhilsaini
OutputThe 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.
Java
// Java program to find the length of the
// longest substring without repeating
// characters
import java.io.*;
import java.util.*;
class GFG{
public static int longestUniqueSubsttr(String str)
{
int n = str.length();
// Result
int res = 0;
for(int i = 0; i < n; i++)
{
// Note : Default values in visited are false
boolean[] visited = new boolean[256];
for(int j = i; j < n; j++)
{
// If current character is visited
// Break the loop
if (visited[str.charAt(j)] == true)
break;
// Else update the result if
// this window is larger, and mark
// current character as visited.
else
{
res = Math.max(res, j - i + 1);
visited[str.charAt(j)] = true;
}
}
// Remove the first character of previous
// window
visited[str.charAt(i)] = false;
}
return res;
}
// Driver code
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.println("The input string is " + str);
int len = longestUniqueSubsttr(str);
System.out.println("The length of the longest " +
"non-repeating character " +
"substring is " + len);
}
}
// This code is contributed by akhilsaini
OutputThe input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Method 3 ( Linear Time ): Using this solution the problem can be solved in linear time using the window sliding technique. Whenever we see repetition, we remove the window till the repeated string.
Java
import java.io.*;
class GFG {
public static int longestUniqueSubsttr(String str)
{
String test = "";
// Result
int maxLength = -1;
// Return zero if string is empty
if (str.isEmpty()) {
return 0;
}
// Return one if string length is one
else if (str.length() == 1) {
return 1;
}
for (char c : str.toCharArray()) {
String current = String.valueOf(c);
// If string already contains the character
// Then substring after repeating character
if (test.contains(current)) {
test = test.substring(test.indexOf(current)
+ 1);
}
test = test + String.valueOf(c);
maxLength = Math.max(test.length(), maxLength);
}
return maxLength;
}
// Driver code
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.println("The input string is " + str);
int len = longestUniqueSubsttr(str);
System.out.println("The length of the longest "
+ "non-repeating character "
+ "substring is " + len);
}
}
// This code is contributed by Alex Bennet
OutputThe 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 :
Java
// Java program to find the length of the longest substring
// without repeating characters
import java.util.*;
public class GFG {
static final int NO_OF_CHARS = 256;
static int longestUniqueSubsttr(String str)
{
int n = str.length();
int res = 0; // result
// last index of all characters is initialized
// as -1
int [] lastIndex = new int[NO_OF_CHARS];
Arrays.fill(lastIndex, -1);
// Initialize start of current window
int i = 0;
// Move end of current window
for (int j = 0; j < n; j++) {
// Find the last index of str[j]
// Update i (starting index of current window)
// as maximum of current value of i and last
// index plus 1
i = Math.max(i, lastIndex[str.charAt(j)] + 1);
// Update result if we get a larger window
res = Math.max(res, j - i + 1);
// Update last index of j.
lastIndex[str.charAt(j)] = j;
}
return res;
}
/* Driver program to test above function */
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.println("The input string is " + str);
int len = longestUniqueSubsttr(str);
System.out.println("The length of "
+ "the longest non repeating character is " + len);
}
}
// This code is contributed by Sumit Ghosh
OutputThe 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 :
Java
import java.util.*;
class GFG {
static int longestUniqueSubsttr(String s)
{
// Creating a set to store the last positions of occurrence
HashMap<Character, Integer> seen = new HashMap<>();
int maximum_length = 0;
// starting the initial point of window to index 0
int start = 0;
for(int end = 0; end < s.length(); end++)
{
// Checking if we have already seen the element or not
if(seen.containsKey(s.charAt(end)))
{
// If we have seen the number, move the start pointer
// to position after the last occurrence
start = Math.max(start, seen.get(s.charAt(end)) + 1);
}
// Updating the last seen value of the character
seen.put(s.charAt(end), end);
maximum_length = Math.max(maximum_length, end-start + 1);
}
return maximum_length;
}
// Driver code
public static void main(String []args)
{
String s = "geeksforgeeks";
System.out.println("The input String is " + s);
int length = longestUniqueSubsttr(s);
System.out.println("The length of the longest non-repeating character substring is " + length);
}
}
// This code is contributed by rutvik_56.
OutputThe 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!
Similar Reads
How to Find the Longest Common Prefix of Two Strings in Java?
In this article, we will find the longest common prefix of two Strings in Java. Examples: Input: String 1= geeksforgeeks, String 2 = geezerOutput: âgeeâ Input: String 1= flower, String 2 = flightOutput: âflâ Methods to Find the Longest common Prefix of two Strings in JavaBelow are the methods by whi
4 min read
How to Replace the Last Occurrence of a Substring in a String in Java?
In this article, we will learn about replacing the last instance of a certain substring inside a string as a typical need. We'll look at a practical Java solution for this in this post. Replace the last occurrence of a Substring in a String in JavaWe may use the lastIndexOf() method to determine the
2 min read
Java Program To Check If A String Is Substring Of Another
Write a java program for a given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples : Input: s1 = "for", s2 = "geeksforgeeks"Output: 5Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2
3 min read
Java Program To Find Longest Common Prefix Using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings
2 min read
Java Program to Find All Palindromic Sub-Strings of a String
Given a string, the task is to count all palindrome substring in a given string. Input : aba Output : 4 Explanation : All palindrome substring are : "aba" , "a" , "b", "a" Input : TENET Output : 7 Explanation : All palindrome sub-string are : "T" , "E" , "N", "E", "T" , "ENE" , "TENET" Approach: Tak
2 min read
Java Program for Longest subsequence of a number having same left and right rotation
Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101"
4 min read
How to find the first and last character of a string in Java
Given a string str, the task is to print the first and the last character of the string. Examples: Input: str = "GeeksForGeeks" Output: First: G Last: s Explanation: The first character of the given string is 'G' and the last character of given string is 's'. Input: str = "Java" Output: First: J Las
3 min read
Java Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {âgeeksforgeeksâ, âgeeksâ, âgeekâ, âgeezerâ} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on âPRACTICE â first, before moving on to the solution. We start with an example. Suppose
5 min read
How to Split a String into Equal Length Substrings in Java?
In Java, splitting a string into smaller substrings of equal length is useful for processing large strings in manageable pieces. We can do this with the substring method of the loop. This method extracts a substring of the specified length from the input string and stores it in a list.Example:In the
3 min read
Remove first and last character of a string in Java
Given a string str, the task is to write the Java Program to remove the first and the last character of the string and print the modified string.Examples:Input: str = "GeeksForGeeks"Output: "eeksForGeek"Explanation: The first and last characters of the given string are 'G' and 's' respectively. Afte
4 min read