Find Length of Longest Substring Without Repeating Characters in Java



In Java, substrings are part of the string which contains the continuous character of the string of any length from 1 to complete string. We are given a string and we have to find the length of the largest substring from the given string that only contains the unique characters. We will see three types of methods: finding every substring, sliding windows, and two-pointers.

Problem Statement

Given a string, write a Java program to find length of the longest substring without repeating characters ?

Input

thisisthegivenstring

Output

The length of the longest substring that contains only unique characters is: 8

Approaches to Find Length of the Longest Substring Without Repeating Characters

Approach 1: Finding every substring

In this approach, we will get every substring and then will check if there are any repeated characters present or not. Below are the steps ?

  • Define a function isUnique to check if a substring has unique characters.
  • Use a boolean array to mark non-unique characters.
  • Traverse the substring and check for repeated characters.
  • If no repeats, return true.
  • Define another function longestSubStr to find the longest substring with unique characters.
  • Traverse the string and get every substring.
  • Call isUnique for each substring and update the maximum length.
  • Return the maximum length.

Example

public class Solution{
   // function to check the unique characters 
   public static boolean isUnique(String str, int i, int j){
      // array to store the non-unique characters 
      boolean arr[] = new boolean[26];        
      // traversing over the string 
      while(i <= j){
         if(arr[str.charAt(i)-'a'] == true){
            return false; // returning false as answer 
         }
         else{
            arr[str.charAt(i)-'a'] = true;
         }
         i++;
      }
      return true; // returning true 
   }    
   // function to get the required substring 
   public static int longestSubStr(String str){
      int len = str.length();  
      int ans = 0; // variable to store the answer         
      // traversing over the string 
      for(int i=0; i<len; i++){            
         // function to get every substring starting from here
         for(int j = i; j<len; j++){                
            // calling function to check if the current substring contains the unique characters 
            if(isUnique(str, i,j)){
               ans = Math.max(ans, j-i+1);
            }
         }
      }
      return ans; // return the final answer 
   }    
   // main function 
   public static void main(String []args){
   String str = "thisisthegivenstring"; // given string     
   // calling to the function 
   int ans = longestSubStr(str);    
   // print the final answer 
   System.out.println("The length of the longest substring that contains only unique characters is: " + ans );
   }
}

Output

The length of the longest substring that contains only unique characters is: 8

Time and Space Complexity

The time complexity of the above code is O(N^3), where N is the length of the given string.

The space complexity of the above code is constant or O(1), as we are not using any extra space here.

Approach 2: Sliding windows

In this approach, we will create a window by using the pointers and will traverse over the string until the window does not have any repetitive characters. Below are the steps ?

  • Define a function longestSubStr to find the longest substring with unique characters.
  • Traverse the string str from index i to len using for loop.
  • Create a boolean array arr to store non-unique characters.
  • Initialize two pointers, i and j, to the start of the window.
  • Expand the window by moving j to the right.
  • If a repeated character is found, break the loop and move i to the right.
  • Update the maximum length ans if the current window has unique characters.
  • Repeat steps 5-7 until the end of the string is reached.
  • Return the maximum length ans.

Example

public class Solution{    
   // function to get the required substring 
   public static int longestSubStr(String str){
      int len = str.length(); 
      int ans = 0; // variable to store the answer         
      // traversing over the string 
      for(int i=0; i<len; i++){            
         // array to store the non-unique characters 
         boolean arr[] = new boolean[26];            
         // function to get every substring starting from here
         for(int j = i; j<len; j++){
            if(arr[str.charAt(j)-'a'] == true){
               break;
            }
            else{
               arr[str.charAt(j)-'a'] = true;
               ans = Math.max(ans,j-i+1);
            }
         }
      }
      return ans; // return the final answer 
   }    
   // main function 
   public static void main(String []args){
   String str = "thisisthegivenstring"; // given string 
    
   // calling to the function 
   int ans = longestSubStr(str);    
   // print the final answer 
   System.out.println("The length of the longest substring that contains only unique characters is: " + ans );
   }
}

Output

The length of the longest substring that contains only unique characters is: 8

Time and Space Complexity

The time complexity of the above code is O(N^2), where N is the length of the given string.

The space complexity of the above code is constant or O(1), as we are not using any extra space here.

Approach 3: Two-pointers

In this approach, we will use the concept of the two pointers and move one pointer slow and another fast and update the slow pointer to the index where the previous occurrence of the current character exists. Below are the steps ?

  • Define a function longestSubStr to find the longest substring with unique characters.
  • Initialize an array arr to store the last index of each character.
  • Fill the array with -1.
  • Initialize two pointers, i (slow) and j (fast), to 0.
  • Traverse the string str with the fast pointer j.
  • Update the slow pointer i to the maximum of its current value and the last index of the current character + 1.
  • Update the answer ans to the maximum of its current value and the length of the current substring (j - i + 1).
  • Update the last index of the current character in the array arr.
  • Repeat steps 5-8 until the end of the string is reached.
  • Return the answer ans.

Example

import java.util.*; 
public class Solution{    
   // function to get the required substring 
   public static int longestSubStr(String str){
      int len = str.length(); // getting the length of the string 
      int ans = 0; // variable to store the answer         
      int arr[] = new int[26]; // array to store the last index of the current character 
      Arrays.fill(arr, -1); // function to fill -1 at each index  
      int i = 0; // last pointer or slow pointer 
      // fast pointer, traversing over the string
      for(int j = 0; j < len; j++){ 
         // updating the value of the slow pointer 
         i = Math.max(i, arr[str.charAt(j)-'a'] + 1);            
         // updating the answer
         ans = Math.max(ans, j - i + 1); 
         // updating the index of the current character
         arr[str.charAt(j) - 'a'] = j;
      }        
      return ans; // return the final answer 
   }    
   // main function 
   public static void main(String []args){
   String str = "thisisthegivenstring"; // given string     
   // calling to the function 
   int ans = longestSubStr(str);    
   // print the final answer 
   System.out.println("The length of the longest substring that contains only unique characters is: " + ans );
   }
}

Output

The length of the longest substring that contains only unique characters is: 8

Time and Space Complexity

The time complexity of the above code is O(N), where N is the length of the given string.

The space complexity of the above code is constant or O(1), as we are not using any extra space here.

Conclusion

In this tutorial, we have implemented a Java program to find the length of the longest substring without repeating characters. We have implemented three approaches: first is finding every substring with the time complexity of the O(N^3), second is using the sliding window which take the time of O(N^2), and third is two pointers approach.

Updated on: 2024-07-24T11:43:39+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements