Count of substrings of a string containing another given string as a substring | Set 2
Last Updated :
30 Aug, 2022
Given two strings S and T of length N and M respectively, the task is to count the number of substrings of S that contains the string T in it as a substring.
Examples:
Input: S = “dabc”, T = “ab”
Output: 4
Explanation:
Substrings of S containing T as a substring are:
- S[0, 2] = “dab”
- S[1, 2] = “ab”
- S[1, 3] = “abc”
- S[0, 3] = “dabc”
Input: S = “hshshshs” T = “hs”
Output: 25
Naive Approach: For the simplest approach to solve the problem, refer to the previous post of this article.
Time Complexity: O(N2)
Auxiliary Space: O(N2)
Efficient Approach: To optimize the above approach, the idea is to find out all the occurrences of T in S. Whenever T is found in S, add all the substrings which contain this occurrence of T excluding the substrings which were already calculated in the previous occurrences. Follow the steps below to solve the problem:
- Initialize a variable, say answer, to store the count of substrings.
- Initialize a variable, say last, to store the starting index of the last occurrence of T in S.
- Iterate over the range [0, N - M] using a variable, say i.
- Check if the substring S[i, i + M] is equal to T or not. If found to be true, then add (i + 1 - last) * (N - (i + M - 1)) to answer and update last to (i + 1).
- Otherwise, continue for the next iteration.
- After completing the above steps, print the value of the answer as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the substrings of
// string containing another given
// string as a substring
void findOccurrences(string S, string T)
{
// Store length of string S
int n1 = S.size();
// Store length of string T
int n2 = T.size();
// Store the required count of
// substrings
int ans = 0;
// Store the starting index of
// last occurrence of T in S
int last = 0;
// Iterate in range [0, n1-n2]
for (int i = 0; i <= n1 - n2; i++) {
// Check if substring from i
// to i + n2 is equal to T
bool chk = true;
// Check if substring from i
// to i + n2 is equal to T
for (int j = 0; j < n2; j++) {
// Mark chk as false and
// break the loop
if (T[j] != S[i + j]) {
chk = false;
break;
}
}
// If chk is true
if (chk) {
// Add (i + 1 - last) *
// (n1 - (i + n2 - 1))
// to answer
ans += (i + 1 - last)
* (n1 - (i + n2 - 1));
// Update the last to i + 1
last = i + 1;
}
}
// Print the answer
cout << ans;
}
// Driver code
int main()
{
string S = "dabc", T = "ab";
// Function Call
findOccurrences(S, T);
}
Java
// Java program for the above approach
class GFG{
// Function to count the substrings of
// string containing another given
// string as a substring
static void findOccurrences(String S, String T)
{
// Store length of string S
int n1 = S.length();
// Store length of string T
int n2 = T.length();
// Store the required count of
// substrings
int ans = 0;
// Store the starting index of
// last occurrence of T in S
int last = 0;
// Iterate in range [0, n1-n2]
for (int i = 0; i <= n1 - n2; i++)
{
// Check if substring from i
// to i + n2 is equal to T
boolean chk = true;
// Check if substring from i
// to i + n2 is equal to T
for (int j = 0; j < n2; j++)
{
// Mark chk as false and
// break the loop
if (T.charAt(j) != S.charAt(i + j))
{
chk = false;
break;
}
}
// If chk is true
if (chk)
{
// Add (i + 1 - last) *
// (n1 - (i + n2 - 1))
// to answer
ans += (i + 1 - last)
* (n1 - (i + n2 - 1));
// Update the last to i + 1
last = i + 1;
}
}
// Print the answer
System.out.println(ans);
}
// Driver code
public static void main (String[] args)
{
String S = "dabc", T = "ab";
// Function Call
findOccurrences(S, T);
}
}
// This code is contributed by AnkThon
Python3
# Python3 program for the above approach
# Function to count the substrings of
# containing another given
# as a sub
def findOccurrences(S, T):
# Store length of S
n1 = len(S)
# Store length of T
n2 = len(T)
# Store the required count of
# substrings
ans = 0
# Store the starting index of
# last occurrence of T in S
last = 0
# Iterate in range [0, n1-n2]
for i in range(n1 - n2 + 1):
# Check if subfrom i
# to i + n2 is equal to T
chk = True
# Check if subfrom i
# to i + n2 is equal to T
for j in range(n2):
# Mark chk as false and
# break the loop
if (T[j] != S[i + j]):
chk = False
break
# If chk is true
if (chk):
# Add (i + 1 - last) *
# (n1 - (i + n2 - 1))
# to answer
ans += (i + 1 - last) * (n1 - (i + n2 - 1))
# Update the last to i + 1
last = i + 1
# Print the answer
print(ans)
# Driver code
if __name__ == '__main__':
S,T = "dabc","ab"
# Function Call
findOccurrences(S, T)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
class GFG
{
// Function to count the substrings of
// string containing another given
// string as a substring
static void findOccurrences(String S, String T)
{
// Store length of string S
int n1 = S.Length;
// Store length of string T
int n2 = T.Length;
// Store the required count of
// substrings
int ans = 0;
// Store the starting index of
// last occurrence of T in S
int last = 0;
// Iterate in range [0, n1-n2]
for (int i = 0; i <= n1 - n2; i++)
{
// Check if substring from i
// to i + n2 is equal to T
bool chk = true;
// Check if substring from i
// to i + n2 is equal to T
for (int j = 0; j < n2; j++)
{
// Mark chk as false and
// break the loop
if (T[j] != S[i + j])
{
chk = false;
break;
}
}
// If chk is true
if (chk)
{
// Add (i + 1 - last) *
// (n1 - (i + n2 - 1))
// to answer
ans += (i + 1 - last)
* (n1 - (i + n2 - 1));
// Update the last to i + 1
last = i + 1;
}
}
// Print the answer
Console.WriteLine(ans);
}
// Driver code
public static void Main(String[] args)
{
String S = "dabc", T = "ab";
// Function Call
findOccurrences(S, T);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program for above approach
// Function to count the substrings of
// string containing another given
// string as a substring
function findOccurrences(S, T)
{
// Store length of string S
let n1 = S.length;
// Store length of string T
let n2 = T.length;
// Store the required count of
// substrings
let ans = 0;
// Store the starting index of
// last occurrence of T in S
let last = 0;
// Iterate in range [0, n1-n2]
for (let i = 0; i <= n1 - n2; i++)
{
// Check if substring from i
// to i + n2 is equal to T
let chk = true;
// Check if substring from i
// to i + n2 is equal to T
for (let j = 0; j < n2; j++)
{
// Mark chk as false and
// break the loop
if (T[j] != S[i + j])
{
chk = false;
break;
}
}
// If chk is true
if (chk)
{
// Add (i + 1 - last) *
// (n1 - (i + n2 - 1))
// to answer
ans += (i + 1 - last)
* (n1 - (i + n2 - 1));
// Update the last to i + 1
last = i + 1;
}
}
// Print the answer
document.write(ans);
}
// Driver Code
let S = "dabc", T = "ab";
// Function Call
findOccurrences(S, T);
</script>
Time Complexity: O(N*M) since two nested loops are used where N and M are the lengths of given strings.
Auxiliary Space: O(1) since no extra array is used the space occupied by the algorithm is constant.
Similar Reads
Count of substrings of a string containing another given string as a substring Given two strings S and T, the task is to count the number of substrings of S that contains string T in it as a substring. Examples: Input: S = "dabc", T = "ab"Output: 4Explanation: Substrings of S containing T as a substring are: S[0, 2] = âdabâS[1, 2] = âabâS[1, 3] = âabcâS[0, 3] = âdabcâ Input: S
8 min read
Count of substrings from given Ternary strings containing characters at least once Given string str of size N consisting of only 0, 1, and 2, the task is to find the number of substrings that consists of characters 0, 1, and 2 at least once. Examples: Input: str = "0122"Output: 2Explanation:There exists 2 substrings such that the substrings has characters 0, 1, 2 at least once is
6 min read
Count number of substrings of a string consisting of same characters Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of su
6 min read
Count of substrings containing only the given character Given a string S and a character C, the task is to count the number of substrings of S that contains only the character C.Examples: Input: S = "0110111", C = '1' Output: 9 Explanation: The substrings containing only '1' are: "1" â 5 times "11" â 3 times "111" â 1 time Hence, the count is 9. Input: S
6 min read
Count of substrings formed using a given set of characters only Given a string str and an array arr[] of K characters, the task is to find the number of substrings of str that contain characters only from the given character array arr[]. Note: The string str and the arr[] contain only lowercase alphabets. Examples: Input: S = "abcb", K = 2, charArray[] = {'a', '
8 min read
Count substrings of same length differing by a single character from two given strings Given two strings S and T of length N and M respectively, the task is to count the number of ways of obtaining same-length substring from both the strings such that they have a single different character. Examples: Input: S = "ab", T = "bb"Output: 3Explanation: The following are the pairs of substri
7 min read
Count of substrings of a given Binary string with all characters same Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = â011âOutput: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
10 min read
Count of Reverse Bitonic Substrings in a given String Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string. Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns: Strictly IncreasingStrictly decreasingDecreasing and then increasin
8 min read
Count of distinct substrings of a string using Suffix Array Given a string of length n of lowercase alphabet characters, we need to count total number of distinct substrings of this string. Examples: Input : str = âababaâ Output : 10 Total number of distinct substring are 10, which are, "", "a", "b", "ab", "ba", "aba", "bab", "abab", "baba" and "ababa"Reco
15+ min read
Count of substrings which contains a given character K times Given a string consisting of numerical alphabets, a character C and an integer K, the task is to find the number of possible substrings which contains the character C exactly K times. Examples: Input : str = "212", c = '2', k = 1 Output : 4 Possible substrings are {"2", "21", "12", "2"} that contain
9 min read