Count substrings that starts with character X and ends with character Y Last Updated : 31 Jan, 2023 Summarize Comments Improve Suggest changes Share Like Article Like Report Given a string str of n lowercase characters, the task is to count the number of substrings of str starting with character X and ending with character Y. Examples: Input: str = "abbcaceghcak" x = 'a', y = 'c' Output: 5 abbc, abbcac, ac, abbcaceghc, aceghc Input: str = "geeksforgeeks" x = 'g', y = 'e' Output: 6 Approach: Initialize two counters i.e. tot_count to count the total number of substrings and count_x to count the number of strings that start with X.Start traversing the string.If the current character is X then increment the count of count_x.If the current character is Y, it means a string ends at Y so increment the count of tot_count i.e. tot_count = tot_count + count_xIt means that if there exists a Y then it will make a substring with all the X occurs before Y in the string. So, add the count of X to the total count.Return total count. Below is the implementation of above approach: C++ // C++ implementation to count substrings // starting with character X and ending // with character Y #include <bits/stdc++.h> using namespace std; // function to count substrings starting with // character X and ending with character Y int countSubstr(string str, int n, char x, char y) { // to store total count of // required substrings int tot_count = 0; // to store count of character 'x' // up to the point the string 'str' // has been traversed so far int count_x = 0; // traverse 'str' from left to right for (int i = 0; i < n; i++) { // if true, increment 'count_x' if (str[i] == x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str[i] == y) tot_count += count_x; } // required count return tot_count; } // Driver code int main() { string str = "abbcaceghcak"; int n = str.size(); char x = 'a', y = 'c'; cout << "Count = " << countSubstr(str, n, x, y); return 0; } Java // Java implementation to count // substrings starting with // character X and ending // with character Y import java.util.*; import java.lang.*; import java.io.*; class GFG { // function to count substrings // starting with character X and // ending with character Y static int countSubstr(String str, int n, char x, char y) { // to store total count of // required substrings int tot_count = 0; // to store count of character // 'x' up to the point the // string 'str' has been // traversed so far int count_x = 0; // traverse 'str' from // left to right for (int i = 0; i < n; i++) { // if true, increment 'count_x' if (str.charAt(i) == x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str.charAt(i) == y) tot_count += count_x; } // required count return tot_count; } // Driver code public static void main(String args[]) { String str = "abbcaceghcak"; int n = str.length(); char x = 'a', y = 'c'; System.out.print ("Count = " + countSubstr(str, n, x, y)); } } // This code is contributed // by Subhadeep Python3 # Python 3 implementation to count substrings # starting with character X and ending # with character Y # function to count substrings starting with # character X and ending with character Y def countSubstr(str, n, x, y): # to store total count of # required substrings tot_count = 0 # to store count of character 'x' # up to the point the string 'str' # has been traversed so far count_x = 0 # traverse 'str' from left to right for i in range(n): # if true, increment 'count_x' if str[i] == x: count_x += 1 # if true accumulate 'count_x' # to 'tot_count' if str[i] == y: tot_count += count_x # required count return tot_count # Driver Code str = 'abbcaceghcak' n = len(str) x, y = 'a', 'c' print('Count =', countSubstr(str, n, x, y)) # This code is contributed SamyuktaSHegde C# // C# implementation to count substrings // starting with character X and ending // with character Y using System; class GFG { // function to count substrings starting // with character X and ending with character Y static int countSubstr(string str, int n, char x, char y) { // to store total count of // required substrings int tot_count = 0; // to store count of character 'x' up // to the point the string 'str' has // been traversed so far int count_x = 0; // traverse 'str' from left to right for (int i = 0; i < n; i++) { // if true, increment 'count_x' if (str[i] == x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str[i] == y) tot_count += count_x; } // required count return tot_count; } // Driver code public static void Main() { string str = "abbcaceghcak"; int n = str.Length; char x = 'a', y = 'c'; Console.Write("Count = " + countSubstr(str, n, x, y)); } } // This code is contributed // by Akanksha Rai PHP <?php // PHP implementation to count substrings // starting with character X and ending // with character Y // function to count substrings starting with // character X and ending with character Y function countSubstr($str, $n, $x, $y) { // to store total count of // required substrings $tot_count = 0; // to store count of character 'x' // up to the point the string 'str' // has been traversed so far $count_x = 0; // traverse 'str' from left to right for ($i = 0; $i < $n; $i++) { // if true, increment 'count_x' if ($str[$i] == $x) $count_x++; // if true accumulate 'count_x' // to 'tot_count' if ($str[$i] == $y) $tot_count += $count_x; } // required count return $tot_count; } // Driver code $str = "abbcaceghcak"; $n = strlen($str); $x = 'a'; $y = 'c'; echo "Count = ". countSubstr($str, $n, $x, $y); // This code is contributed // by Akanksha Rai JavaScript <script> // JavaScript implementation to count substrings // starting with character X and ending // with character Y // function to count substrings starting with // character X and ending with character Y function countSubstr(str, n, x, y) { // to store total count of // required substrings var tot_count = 0; // to store count of character 'x' // up to the point the string 'str' // has been traversed so far var count_x = 0; // traverse 'str' from left to right for (var i = 0; i < n; i++) { // if true, increment 'count_x' if (str[i] === x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str[i] === y) tot_count += count_x; } // required count return tot_count; } // Driver code var str = "abbcaceghcak"; var n = str.length; var x = "a", y = "c"; document.write("Count = " + countSubstr(str, n, x, y)); </script> OutputCount = 5 Complexity Analysis: Time Complexity: O(n), to iterate over the array where n is the size of the given stringAuxiliary Space: O(1),as no extra space is required Comment More infoAdvertise with us Next Article Count substrings that starts with character X and ends with character Y A ayushjauhari14 Follow Improve Article Tags : Strings DSA Practice Tags : Strings 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 12 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. Merge 14 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 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 fir 8 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 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). Binary Search AlgorithmConditions to apply Binary Searc 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 Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 4 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 Like