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
import java.io.*;
import java.util.*;
class GFG{
public static Boolean areDistinct(String str,
int i, int j)
{
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 ;
}
public static int longestUniqueSubsttr(String str)
{
int n = str.length();
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;
}
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);
}
}
|
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.
Java
import java.io.*;
import java.util.*;
class GFG{
public static int longestUniqueSubsttr(String str)
{
int n = str.length();
int res = 0 ;
for ( int i = 0 ; i < n; i++)
{
boolean [] visited = new boolean [ 256 ];
for ( int j = i; j < n; j++)
{
if (visited[str.charAt(j)] == true )
break ;
else
{
res = Math.max(res, j - i + 1 );
visited[str.charAt(j)] = true ;
}
}
visited[str.charAt(i)] = false ;
}
return res;
}
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);
}
}
|
Output
The 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 = "" ;
int maxLength = - 1 ;
if (str.isEmpty()) {
return 0 ;
}
else if (str.length() == 1 ) {
return 1 ;
}
for ( char c : str.toCharArray()) {
String current = String.valueOf(c);
if (test.contains(current)) {
test = test.substring(test.indexOf(current)
+ 1 );
}
test = test + String.valueOf(c);
maxLength = Math.max(test.length(), maxLength);
}
return maxLength;
}
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);
}
}
|
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 :
Java
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 ;
int [] lastIndex = new int [NO_OF_CHARS];
Arrays.fill(lastIndex, - 1 );
int i = 0 ;
for ( int j = 0 ; j < n; j++) {
i = Math.max(i, lastIndex[str.charAt(j)] + 1 );
res = Math.max(res, j - i + 1 );
lastIndex[str.charAt(j)] = j;
}
return res;
}
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);
}
}
|
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 :
Java
import java.util.*;
class GFG {
static int longestUniqueSubsttr(String s)
{
HashMap<Character, Integer> seen = new HashMap<>();
int maximum_length = 0 ;
int start = 0 ;
for ( int end = 0 ; end < s.length(); end++)
{
if (seen.containsKey(s.charAt(end)))
{
start = Math.max(start, seen.get(s.charAt(end)) + 1 );
}
seen.put(s.charAt(end), end);
maximum_length = Math.max(maximum_length, end-start + 1 );
}
return maximum_length;
}
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);
}
}
|
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!
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
13 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Conditions to apply Binary Search Algorithm in a Data S
15+ min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
8 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read