Skip to content
Related Articles

Related Articles

Longest substring that starts with X and ends with Y
  • Last Updated : 07 May, 2021

Given a string str, two characters X and Y. The task is to find the length of the longest substring that starts with X and ends with Y. It is given that there always exists a substring that starts with X and ends with Y
Examples: 
 

Input: str = “QWERTYASDFZXCV”, X = ‘A’, Y = ‘Z’ 
Output:
Explanation: 
The largest substring which start with ‘A’ and end with ‘Z’ = “ASDFZ”. 
Size of the substring = 5.
Input: str = “ZABCZ”, X = ‘Z’, Y = ‘Z’ 
Output:
Explanation: 
The largest substring which start with ‘Z’ and end with ‘Z’ = “ZABCZ”. 
Size of the substring = 5. 
 

Naive Approach: The naive approach is to find all the substrings of the given string out of these find the largest substring which starts with X and ends with Y
Time Complexity: O(N2
Auxiliary Space: O(1)
Efficient Approach: To optimized the above approach, the count of characters between X and Y should be the largest. So, iterate over the string using pointers start and end to find the first occurrence of X from the starting index and the last occurrence of Y from the end. Below are the steps: 
 

  1. Initialize start = 0 and end = length of string – 1.
  2. Traverse the string from the beginning and find the first occurrence of character X. Let it be at index xPos.
  3. Traverse the string from the beginning and find the last occurrence of character Y. Let it be at index yPos.
  4. The length of the longest substring is given by (yPos – xPos + 1).

Below is the implementation of the above approach:
 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function returns length of longest
// substring starting with X and
// ending with Y
int longestSubstring(string str,
                    char X, char Y)
{
    // Length of string
    int N = str.length();
    int start = 0;
    int end = N - 1;
    int xPos = 0;
    int yPos = 0;
 
    // Find the length of the string
    // starting with X from the beginning
    while (true) {
 
        if (str[start] == X) {
            xPos = start;
            break;
        }
        start++;
    }
 
    // Find the length of the string
    // ending with Y from the end
    while (true) {
 
        if (str[end] == Y) {
            yPos = end;
            break;
        }
        end--;
    }
 
    // Longest substring
    int length = (yPos - xPos) + 1;
 
    // Print the length
    cout << length;
}
 
// Driver Code
int main()
{
    // Given string str
    string str = "HASFJGHOGAKZZFEGA";
 
    // Starting and Ending characters
    char X = 'A', Y = 'Z';
 
    // Function Call
    longestSubstring(str, X, Y);
    return 0;
}

Java




// Java program for the above approach
class GFG{
     
// Function returns length of longest
// substring starting with X and
// ending with Y
public static void longestSubstring(String str,
                                    char X, char Y)
{
     
    // Length of string
    int N = str.length();
    int start = 0;
    int end = N - 1;
    int xPos = 0;
    int yPos = 0;
     
    // Find the length of the string
    // starting with X from the beginning
    while (true)
    {
        if (str.charAt(start) == X)
        {
            xPos = start;
            break;
        }
        start++;
    }
     
    // Find the length of the string
    // ending with Y from the end
    while (true)
    {
        if (str.charAt(end) == Y)
        {
            yPos = end;
            break;
        }
        end--;
    }
     
    // Longest substring
    int length = (yPos - xPos) + 1;
     
    // Print the length
    System.out.print(length);
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given string str
    String str = "HASFJGHOGAKZZFEGA";
     
    // Starting and Ending characters
    char X = 'A', Y = 'Z';
     
    // Function Call
    longestSubstring(str, X, Y);
}
}
 
// This code is contributed by divyeshrabadiya07

Python3




# Python3 program for the above approach
 
# Function returns length of longest
# substring starting with X and
# ending with Y
def longestSubstring(str, X, Y):
     
    # Length of string
    N = len(str)
     
    start = 0
    end = N - 1
    xPos = 0
    yPos = 0
 
    # Find the length of the string
    # starting with X from the beginning
    while (True):
        if (str[start] == X):
            xPos = start
            break
             
        start += 1
 
    # Find the length of the string
    # ending with Y from the end
    while (True):
        if (str[end] == Y):
            yPos = end
            break
         
        end -= 1
 
    # Longest substring
    length = (yPos - xPos) + 1
 
    # Print the length
    print(length)
 
# Driver Code
if __name__ == "__main__":
     
    # Given string str
    str = "HASFJGHOGAKZZFEGA"
 
    # Starting and Ending characters
    X = 'A'
    Y = 'Z'
 
    # Function Call
    longestSubstring(str, X, Y)
 
# This code is contributed by sanjoy_62

C#




// C# program for the above approach 
using System;
 
class GFG{
     
// Function returns length of longest
// substring starting with X and
// ending with Y
static void longestSubstring(string str,
                             char X, char Y)
{
     
    // Length of string
    int N = str.Length;
    int start = 0;
    int end = N - 1;
    int xPos = 0;
    int yPos = 0;
     
    // Find the length of the string
    // starting with X from the beginning
    while (true)
    {
        if (str[start] == X)
        {
            xPos = start;
            break;
        }
        start++;
    }
     
    // Find the length of the string
    // ending with Y from the end
    while (true)
    {
        if (str[end] == Y)
        {
            yPos = end;
            break;
        }
        end--;
    }
     
    // Longest substring
    int length = (yPos - xPos) + 1;
     
    // Print the length
    Console.Write(length);
}
 
// Driver code
public static void Main()
{
     
    // Given string str
    string str = "HASFJGHOGAKZZFEGA";
     
    // Starting and Ending characters
    char X = 'A', Y = 'Z';
     
    // Function call
    longestSubstring(str, X, Y);
}
}
 
// This code is contributed by sanjoy_62

Javascript




<script>
      // JavaScript program for the above approach
      // Function returns length of longest
      // substring starting with X and
      // ending with Y
      function longestSubstring(str, X, Y) {
        // Length of string
        var N = str.length;
        var start = 0;
        var end = N - 1;
        var xPos = 0;
        var yPos = 0;
 
        // Find the length of the string
        // starting with X from the beginning
        while (true) {
          if (str[start] === X) {
            xPos = start;
            break;
          }
          start++;
        }
 
        // Find the length of the string
        // ending with Y from the end
        while (true) {
          if (str[end] === Y) {
            yPos = end;
            break;
          }
          end--;
        }
 
        // Longest substring
        var length = yPos - xPos + 1;
 
        // Print the length
        document.write(length);
      }
 
      // Driver code
      // Given string str
      var str = "HASFJGHOGAKZZFEGA";
 
      // Starting and Ending characters
      var X = "A",
        Y = "Z";
      // Function call
      longestSubstring(str, X, Y);
    </script>
Output: 



12

 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up
Recommended Articles
Page :