VOOZH about

URL: https://www.geeksforgeeks.org/dsa/length-of-longest-substring-having-all-characters-as-k/

⇱ Length of longest substring having all characters as K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Length of longest substring having all characters as K

Last Updated : 29 Apr, 2023

Given a string S and a character K. The task is to find the length of the longest substring of S having all characters the same as character K.

Examples: 

Input: S = "abcd1111aabc", K = '1' 
Output:
Explanation: 
1111 is the largest substring of length 4.

Input: S = "#1234#@@abcd", K = '@' 
Output:
Explanation: 
@@ is the largest substring of length 2.

Approach: The idea is to iterate over the string and check the following two conditions:

  • If the current character is the same as character K then increase the value of the counter by one.
  • If the current character is not the same as K then update the previous count and reinitialize the counter to 0.
  • Repeat the steps above till the length of the string.

Below is the implementation of the above approach:


Output: 
4

Time Complexity: O(N) 
Auxiliary Space: O(1)

Another approach to solve above problem :-

  • Define a function length_substring(S, K) that takes a string S and a character K as input.
  • In the function, initialize left, right, max_len, count, and freq. left and right are pointers that point to the leftmost and rightmost indices of the current substring being considered. max_len is the length of the longest substring found so far. count is the number of characters in the current substring that are not equal to K. freq is a list of 26 elements that stores the frequency of each character in the current substring.
  • While right is less than the length of S, increment the frequency of the character at S[right] in freq. If S[right] is not equal to K, increment count.
  • While count is greater than 0, decrement the frequency of the character at S[left] in freq. If S[left] is not equal to K, decrement count and increment left.
  • Update max_len to be the maximum of max_len and right-left+1.
  • Increment right and repeat steps 3-5 until right is equal to the length of S.
  • Return max_len.

Here is the implementation of above approach:-


Output
4

Time complexity:

  • The while loop runs for each character in the string, so it has a time complexity of O(n).
  • The inner while loop also runs at most n times, so it has a time complexity of O(n) as well.
  • The operations inside the loops are all constant time operations, so they don't affect the time complexity.
  • Therefore, the overall time complexity of the algorithm is O(n).

Space Complexity:

  • The algorithm uses a frequency array of size 26, which is constant space.
  • Therefore, the space complexity of the algorithm is O(1).
     
Comment
Article Tags: