Javatpoint Logo
Javatpoint Logo

Length of the longest substring without repeating characters in Java

The task of discovering the length of the longest substring without repeating characters is a crucial challenge in algorithmic programming. The problem involves identifying the maximum length of a continuous section in a provided string where each character occurs only once. Addressing this challenge in the Java programming landscape necessitates adeptly utilizing string manipulation tools and algorithmic paradigms. The problem is practical in optimizing computational processes, particularly in data compression and string processing scenarios.

Example 1:

Input: "pqrstuvwxy"

Output: 10

Explanation: The entire string "pqrstuvwxy" contains no repeating characters, constituting the longest substring with a length of 10.

Example 2:

Input: "abacabadabacaba"

Output: 4

Explanation: The distinct substrings without repeating characters are "abac" and "bacab," with a length of 4.

Example 3:

Input: "xyzxyzabcd"

Output: 6

Explanation: The longest substrings without repeating characters are "xyzabc" and "yzabcd," both with lengths of 6.

Example 4:

Input: "mississippi"

Output: 4

Explanation: The longest substring without repeating characters is "issi," with a length of 4.

Approach: Using Sliding Window in O(n3) time.

The Sliding Window approach, used to find the longest substring without repeated characters in O(n^3) time, involves moving a window through the text to check for substrings.

Algorithm:

Step 1: Set n as the length of the input string s and the maxLength to 0.

Step 2: Iterate over all possible starting indices of the substring using a loop with index i from 0 to n.

  • For each i, iterate over all possible ending indices of the substring using a nested loop with index j from i + 1 to n.
  • Call the allUnique Method to verify if all characters in the substring from index i to j - 1 are unique.

Step 3: The allUnique Method iterates through the substring using two nested loops, comparing each character with every other character.

Step 4: If a repeated character is found it will return false; otherwise it will return true.

Step 5: If the substring is unique (allUnique returns true), calculate the length of the substring (j - i) and update maxLength with the maximum of its current value and the calculated length.

Step 6: After both loops are complete, return the final value of maxLength as the length of the longest substring without repeating characters.

Step 7: Check if all characters in a given substring (from index start to end - 1) are unique.

  • Use two nested loops to compare each character with every other character in the substring.

Step 8: Display the result of the code.

Implementation:

Filename: LongestSubstring1.java

Output:

Length of the longest substring without repeating characters: 7

Time Complexity: The time complexity of the provided code is O(n^3), where 'n' is the length of the input string.

Auxiliary Space: The auxiliary space complexity is O(1) or constant space. Additionally, the helper method allUnique utilizes only a few local variables, and its space complexity remains constant regardless of the input size.

Approach: Using Sliding Window in O(n2) time:

The Sliding Window approach, employed to find the length of the longest substring without repeating characters in O(n^2) time, efficiently adjusts a window over the input and is suitable for moderately sized inputs.

Algorithm:

Step 1: Import Necessary Packages: Import java.io.* for input/output functionality and the Import java.util.*.

Step 2: Define Method lengthOfLongestSubstring and also the Input of the String s and the Output of the Integer (Maximum length of the substring without repeating characters)

Step 3: Now Initialize Variables. Set n as the length of the input string s and Set maxLength to 0.

Step 4: Begin a loop with index i ranging from 0 to n - 1.

  • For each i in the outer loop, initiate a nested loop with index j ranging from i + 1 to n.

Step 5: Create a boolean array visited of size 256 to keep track of visited characters using ASCII values.

Step 6: For each character at index j:

  • If visited[s.charAt(j)] is true, indicating the character is already visited, break the inner loop.
  • Mark the character as visited by setting visited[s.charAt(j)] to true.

Step 7: If the substring is unique (no repeating characters), calculate the length of the substring (j - i + 1).

Step 8: Update maxLength with the maximum of its current value and the calculated length.

Implementation:

Filename: LongestSubstring2.java

Output:

Length of the longest substring without repeating characters: 7

Time Complexity: The time complexity of the provided code is O(n^2), where 'n' is the length of the input string. It is because the code utilizes nested loops. The outer loop runs 'n' times, and for each iteration of the outer loop, the inner loop runs at most 'n' times.

Auxiliary Space: The auxiliary space complexity is O(1) or constant space.

Approach: Using Binary Search Top of Form

The Binary Search approach is like a smart way of finding things in an organized list. When looking for the length of the longest substring without repeating characters, it helps search for the best length more quickly.

Algortihm

Step 1: Initialize the variable in the code. Set n as the length of the input string s and also the variables low to 1, high to n, and result to 0.

Step 2: While low is less than or equal to high, do the following:

  • Calculate the middle index as mid = (low + high) / 2.

Step 3: Initialize an empty set set to keep track of characters in the current window.

  • Initialize start to 0.
  • Iterate through the input string with ends ranging from 0 to n - 1, and do the following for each character:

Step 4: While the character at the current end violates uniqueness (present in the set):

  • Remove the character at the start to maintain uniqueness.
  • Move the start pointer to the right.

Step 5: Add the current character to the set.

  • Check if the length condition is met (end - start + 1 >= length).
  • If met, return true.

Step 6: If a substring of length mid is possible without repeating characters (isValid returns true), do the following:

  • Update result to mid.
  • Adjust the search space for longer substrings by setting low = mid + 1.

Step 7: If a substring of length mid is not possible, do the following:

  • Adjust the search space for shorter substrings by setting high = mid - 1.

Step 8: After the binary search concludes, return the result's final value as the longest substring's length without repeating characters.

Implementation:

Filename: BinarySearchLongestSubstring.java

Output:

Length of the longest substring without repeating characters: 7

Time Complexity: The code has a time complexity of O(n log n), where "n" is the length of the input string.

Auxiliary Space: The auxiliary space complexity is O(n), where "n" is the length of the input string.

Approach: Using Sliding Window

By using the Sliding Window approach, we can efficiently explore different substrings to find the longest one without any repeating characters.

Algorithm:

Step 1: Initialize the length of the input string is 0, return 0 (no characters to process).

  • If the input string length is 1, return 1 (single character is unique).

Step 2: Initialize the maximum length (maxLength) to 0.

  • Create a boolean array visited of size 256 to keep track of visited characters.

Step 3: Initialize two pointers, leftPointer and rightPointer, both set to 0.

  • Iterate through the input string using the rightPointer.

Step 4: If the character at rightPointer is already visited:

  • Move the leftPointer to the right while marking visited characters as false until the repeating character is no longer part of the current window.
  • Mark the character at rightPointer as visited.
  • Calculate the length of the current window (rightPointer - leftPointer + 1).
  • Update maxLength with the maximum length.

Step 5: The variable maxLength now holds the length of the longest substring without repeating characters.

Step 6: Display the result.

Implementation:

Filename: SlidingWindowLongestSubstring.java

Output:

Given Input String: javatpoint
Length of the Longest Substring without repeating characters: 7

Time Complexity: The time complexity of the provided code is O(N), where N is the length of the input string.

Auxiliary Space Complexity: The auxiliary space complexity is O(1) since the extra space used is independent of the input size.

Approach: Storing the last index of each character

The Index Storage approach involves keeping track of the last index where each character appeared in the text. It helps in efficiently determining the length of the longest substring without any repeated characters.

Algorithm:

Step 1: Initialize n to the length of the input string s.

Step 2: Create an array lastIndex of size 256 to store the last index of each character, initialized with -1 for all characters.

  • Initialize maxLength to 0 to store the maximum length of the substring without repeating characters.
  • Initialize start to 0 to mark the start of the current substring.

Step 3: Start iterating through the characters of the input string using a sliding window approach.

Step 4: Set the end pointer to the initial position, starting from 0 and moving towards the end of the input string (n-1).

Step 5: For each character encountered at the current end index: Check if the Character is Already Present:

  • Check if the character is already present in the current substring:
  • The condition is determined by comparing the lastIndex of the character at the current end index with the start pointer.

Step 6: If the character is already present in the current substring:

  • Update the start pointer to the next index after the last occurrence of the character.
  • It ensures that the sliding window maintains uniqueness and the substring remains without repeating characters.

Step 7: Update the lastIndex of the current character to the end index.

  • It keeps track of the most recent occurrence of each character within the sliding window.

Step 8: Update maxLength by comparing it with the length of the current substring: It ensures that maxLength always stores the length of the longest substring without repeating characters.

Step 9: After the iteration completes, return the final value of maxLength as the length of the longest substring without repeating characters.

Implementation:

Filename: LastIndexLongestSubstring.java

Output:

Length of the longest substring without repeating characters: 7

Time Complexity: The time complexity of the provided code is O(n), where 'n' is the length of the input string.

Auxiliary Space: The auxiliary space complexity is O(1).







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA