The Wayback Machine - https://web.archive.org/web/20240915105403/https://www.geeksforgeeks.org/number-of-substrings-of-one-string-present-in-other/
Open In App

Number of substrings of one string present in other

Last Updated : 07 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Suppose we are given a string s1, we need to the find total number of substring(including multiple occurrences of the same substring) of s1 which are present in string s2. 

Examples: 

Input : s1 = aab
        s2 = aaaab
Output :6
Substrings of s1 are ["a", "a", "b", "aa", 
"ab", "aab"]. These all are present in s2. 
Hence, answer is 6.

Input :s1 = abcd
       s2 = swalencud
Output :3 

The idea is to consider all substrings of s1 and check if it present in s2.  

Implementation:

C++




// CPP program to count number of substrings of s1
// present in s2.
#include<iostream>
#include<string>
using namespace std;
 
int countSubstrs(string s1, string s2)
{
    int ans = 0;
 
    for (int i = 0; i < s1.length(); i++) {
         
        // s3 stores all substrings of s1
        string s3;
        for (int j = i; j < s1.length(); j++) {
            s3 += s1[j];
 
            // check the presence of s3 in s2
            if (s2.find(s3) != string::npos)
                ans++;
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    string s1 = "aab", s2 = "aaaab";
    cout << countSubstrs(s1, s2);
    return 0;
}


Java




// Java program to count number of
// substrings of s1 present in s2.
import java.util.*;
 
class GFG
{
 
static int countSubstrs(String s1,
                        String s2)
{
int ans = 0;
 
for (int i = 0; i < s1.length(); i++)
{
     
    // s3 stores all substrings of s1
    String s3 = "";
    char[] s4 = s1.toCharArray();
    for (int j = i; j < s1.length(); j++)
    {
        s3 += s4[j];
 
        // check the presence of s3 in s2
        if (s2.indexOf(s3) != -1)
            ans++;
    }
}
return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String s1 = "aab", s2 = "aaaab";
    System.out.println(countSubstrs(s1, s2));
}
}
 
// This code is contributed by ChitraNayal


Python 3




# Python 3 program to count number of substrings of s1
# present in s2.
 
# Function for counting no. of substring
# of s1 present in s2
def countSubstrs(s1, s2) :
    ans = 0
    for i in range(len(s1)) :
        s3 = ""
 
        # s3 stores all substrings of s1
        for j in range(i, len(s1)) :
            s3 += s1[j]
 
            # check the presence of s3 in s2
            if s2.find(s3) != -1 :
                ans += 1
    return ans
 
# Driver code
if __name__ == "__main__" :
    s1 = "aab"
    s2 = "aaaab"
 
    # function calling
    print(countSubstrs(s1, s2))
     
# This code is contributed by ANKITRAI1


C#




// C# program to count number of
// substrings of s1 present in s2.
using System;
 
class GFG
{
static int countSubstrs(String s1,
                        String s2)
{
int ans = 0;
 
for (int i = 0; i < s1.Length; i++)
{
     
    // s3 stores all substrings of s1
    String s3 = "";
    char[] s4 = s1.ToCharArray();
    for (int j = i; j < s1.Length; j++)
    {
        s3 += s4[j];
 
        // check the presence of s3 in s2
        if (s2.IndexOf(s3) != -1)
            ans++;
    }
}
return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    String s1 = "aab", s2 = "aaaab";
    Console.WriteLine(countSubstrs(s1, s2));
}
}
 
// This code is contributed
// by Kirti_Mangal


PHP




<?php
// PHP program to count number of
// substrings of s1 present in s2.
 
function countSubstrs($s1, $s2)
{
    $ans = 0;
 
    for ($i = 0; $i < strlen($s1); $i++)
    {
         
        // s3 stores all substrings of s1
        $s3 = "";
        for ($j = $i;
             $j < strlen($s1); $j++)
        {
            $s3 += $s1[$j];
 
            // check the presence of s3 in s2
            if (stripos($s2, $s3, 0) != -1)
                $ans++;
        }
    }
    return $ans;
}
 
// Driver code
$s1 = "aab";
$s2 = "aaaab";
echo countSubstrs($s1, $s2);
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
 
// javascript program to count number of
// substrings of s1 present in s2.
 
function countSubstrs( s1, s2)
{
var ans = 0;
 
for (var i = 0; i < s1.length; i++)
{
     
    // s3 stores all substrings of s1
    var s3 = "";
    var s4 = s1 ;
    for (var j = i; j < s1.length; j++)
    {
        s3 += s4[j];
 
        // check the presence of s3 in s2
        if (s2.indexOf(s3) != -1)
            ans++;
    }
}
return ans;
}
 
// Driver code
 
    var s1 = "aab", s2 = "aaaab";
    document.write(countSubstrs(s1, s2));
 
</script>


Output

6

Complexity Analysis:

  • Time Complexity: O(n*n*n), as nested loops are used where n is the size of string s1
  • Auxiliary Space: O(n), as extra space for string s3 is being used


Similar Reads

Check if a string can be split into 3 substrings such that one of them is a substring of the other two
Given a string S consisting of N lowercase alphabets, the task is to check if it is possible to split the string S into three non-empty substrings such that Y is the substring of the strings X and Z. If it is possible to split the string S then, print "Yes". Otherwise, print "No". Examples: Input: S = "geekseekforgeeks"Output: YesExplanation:The gi
5 min read
Check if a string can be split into two substrings such that one substring is a substring of the other
Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes. Examples : Input: S = "abcdab"Output: YesExplanation: Considering the two splits to be A="abcd" and B="ab", B is a substring of A. Input: S = "abcd"Output: No
5 min read
Find all Characters in given String which are not present in other String
Given two strings str1 and str2, which are of lengths N and M. The second string contains all the characters of the first string, but there are some extra characters as well. The task is to find all the extra characters present in the second string. Examples: Input: str1 = "abcd", str2 = "dabcdehi"Output: d, e, h, iExplanation: [d, e, h, i] are the
10 min read
Check if binary representations of 0 to N are present as substrings in given binary string
Give binary string str and an integer N, the task is to check if the substrings of the string contain all binary representations of non-negative integers less than or equal to the given integer N. Examples: Input: str = “0110", N = 3 Output: True Explanation: Since substrings “0", “1", “10", and “11" can be formed from given string. Hence all binar
9 min read
Find all substrings with even 1s whose reverse is also present in given String
Given a binary string str. The task is to find the size of the set(contains unique substrings) of substrings such that if there is a substring(suppose A) of length n with an even number of 1's and also there is another substring (suppose B) of the same length n and even number of 1's and it is reverse of A, then only A would be considered in the se
7 min read
Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Replace two substrings (of a string) with each other
Given 3 strings S, A and B. The task is to replace every sub-string of S equal to A with B and every sub-string of S equal to B with A. It is possible that two or more sub-strings matching A or B overlap. To avoid confusion about this situation, you should find the leftmost sub-string that matches A or B, replace it, and then continue with the rest
7 min read
Generate string by incrementing character of given string by number present at corresponding index of second string
Given two strings S[] and N[] of the same size, the task is to update string S[] by adding the digit of string N[] of respective indices. Examples: Input: S = "sun", N = "966"Output: bat Input: S = "apple", N = "12580"Output: brute Approach: The idea is to traverse the string S[] from left to right. Get the ASCII value of string N[] and add it to t
4 min read
Sub-strings that start and end with one character and have at least one other
Given the string str which contains only the characters x and y, the task is to count all the sub-strings that start and end with an x and have at least a single y. Examples: Input: str = "xyyxx" Output: 2 "xyyx" and "xyyxx" are the only valid sub-strings. Input: str = "xyy" Output: 0 Approach: Create an array countX[] where countX[i] stores the to
10 min read
Check if one of the numbers is one's complement of the other
Given two non-negative integers a and b. The problem is to check if one of the two numbers is 1's complement of the other. The ones' complement of a binary number is defined as the value obtained by inverting all the bits in the binary representation of the number (swapping 0s for 1s and vice versa). Examples: Input : a = 10, b = 5 Output : Yes (10
6 min read
Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
Given two strings, the task is to check whether the frequencies of a character(for each character) in one string are multiple or a factor in another string. If it is, then output "YES", otherwise output "NO". Examples: Input: s1 = "aabccd", s2 = "bbbaaaacc" Output: YES Frequency of 'a' in s1 and s2 are 2 and 4 respectively, and 2 is a factor of 4 F
6 min read
Minimize operations to make one string contain only characters from other string
Given two strings S1 and S2 containing only lower case English alphabets, the task is to minimize the number of operations required to make S1 contain only characters from S2 where in each operation any character of S1 can be converted to any other letter and the cost of the operation will be difference between those two letters. Examples: Input: S
9 min read
Count of elements in Array which are present K times &amp; their double isn't present
Given an array arr[] of N integers, the task is to find the count of elements in the array that are present K times and their double are not present in the array. Examples: Input: arr[] = {10, 6, 12, 8, 10, 8}, K = 2Output: 2Explanation: 10 is a valid number since it appears exactly two times and 20 does not appear in array.8 is a valid number sinc
9 min read
Count the sum of count of distinct characters present in all Substrings
Given a string S consisting of lowercase English letters of size N where (1 &lt;= N &lt;= 105), the task is to print the sum of the count of distinct characters N where (1 &lt;= N &lt;= 105)in all the substrings. Examples: Input: str = "abbca"Output: 28Explanation: The following are the substrings of "abbca":=&gt; Sum of distinct characters in Subs
8 min read
Count binary strings of length same as given string after removal of substrings "01" and "00" that consists of at least one '1'
Given a binary string S, the task is to count total binary strings consisting of at least one '1' of length equal to the length of the given string after repeatedly removing all occurrences of substrings "10" and "00" from the given string. Examples: Input: S = "111"Output: 7Explanation: Since there are no occurrences of "10" or "01" in the given s
4 min read
Maximum bitwise OR one of any two Substrings of given Binary String
Given a binary string str, the task is to find the maximum possible OR value of any two substrings of the binary string str. Examples: Input: str = "1110010"Output: "1111110"Explanation: On choosing the substring "1110010" and "11100" we get the OR value as "1111110" which is the maximum value. Input: str = "11010"Output: "11111"Explanation: On cho
8 min read
Converting one string to other using append and delete last operations
Given an integer k and two strings str1 and str2 determine whether or not we can convert str1 to str2 by performing exactly k of the below operations on str1. Append a lowercase English alphabetic letter to the end of the str1. Delete the last character in str1 (Performing this operation on an empty string results in an empty string) Examples: Inpu
7 min read
Check if characters of one string can be swapped to form other
Two strings are given, we need to find whether we can form second string by swapping the character of the first string. Examples: Input : str1 = "geeksforgeeks" str2 = "geegeeksksfor" Output : YES Input : str1 = "geeksfor" str2 = "geeekfor" Output : NO First of all, we will find the length of strings and if lengths are not equal that means we can n
6 min read
Check if max occurring character of one string appears same no. of times in other
Given two strings, we need to take the character which has the maximum occurrence in the first string, and then we have to check if that particular character is present in the second string the same number of times as it is present in the first string.Examples: Input : s1 = "sssgeek", s2 = "geeksss" Output : Yes Max occurring character in s1 is 's'
7 min read
Minimum steps to convert one binary string to other only using negation
Given two binary strings A and B, the task is to convert A to B by choosing any sub-string of A and negating it (replace each 0 with 1 and each 1 with 0). Print the minimum number of operations required. Examples: Input: A = "101010", B = "110011" Output: 2 Choose the sub-string of length 2 from index 1 to 2 and negate it then A becomes "110010" an
7 min read
Minimum swaps required between two strings to make one string strictly greater than the other
Given two strings A and B of length M and N respectively, the task is to find the minimum swapping of two characters required to make string A lexicographically greater than the string B. Examples: Input: A = "1432", B = "789", M = 4, N = 3Output: 1Explanation:One possible way is to swap characters at index 0 of both the strings. Therefore, A modif
9 min read
Check if one string can be converted to other using given operation
Given two strings S and T of same length. The task is to determine whether or not we can build a string A(initially empty) equal to string T by performing the below operations. Delete the first character of S and add it at the front of A. Delete the first character of S and add it at the back of A. Examples: Input: S = "abab" T = "baab" Output: YES
15+ min read
Ways of transforming one string to other by removing 0 or more characters
Given two sequences A, B, find out number of unique ways in sequence A, to form a subsequence of A that is identical to sequence B. Transformation is meant by converting string A (by removing 0 or more characters) to string B. Examples: Input : A = "abcccdf", B = "abccdf" Output : 3 Explanation : Three ways will be -&gt; "ab.ccdf", "abc.cdf" &amp;
7 min read
Check if one string is subsequence of other
Given two strings s1 and s2, find if the first string is a Subsequence of the second string, i.e. if s1 is a subsequence of s2. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Examples : Input: s1 = "AXY", s2 = "ADXCPY"Output: True All characters o
10 min read
Minimum value that divides one number and divisible by other
Given two integer p and q, the task is to find the minimum possible number x such that q % x = 0 and x % p = 0. If the conditions aren't true for any number then print -1.Examples: Input: p = 3, q = 99 Output: 3 99 % 3 = 0 3 % 3 = 0Input: p = 2, q = 7 Output: -1 Approach: If a number x satisfies the given condition then it's obvious that q will be
4 min read
Closest pair in an Array such that one number is multiple of the other
Given an array arr[] of integers of size N, the task is to find the closest pair in the given array such that one element is the multiple of the other. If no such pair exists then print -1. Note: Closest pair means the difference between the index of any two elements must be minimum. Examples: Input: arr[] = {2, 3, 4, 5, 6}Output: 2 4Explanation: T
6 min read
Changing One Clock Time to Other Time in Minimum Number of Operations
Given two clock times (in HH:MM:SS format), change one time to other time in minimum number of operations. Here one operation is meant by shifting the hour, minute or second clock hand by 1 unit in either directions. The program follows all the basic rules of a clock for eg.: changing second's hand from 59 to 0 will make 1 unit change for minute ha
15 min read
Number of turns to reach from one node to other in binary tree
Given a binary tree and two nodes. The task is to count the number of turns needed to reach from one node to another node of the Binary tree. Examples: Input: Below Binary Tree and two nodes 5 &amp; 6 1 / \ 2 3 / \ / \ 4 5 6 7 / / \ 8 9 10 Output: Number of Turns needed to reach from 5 to 6: 3 Input: For above tree if two nodes are 1 &amp; 4 Output
15+ min read
Count the number of arrays formed by rearranging elements such that one adjacent element is multiple of other
Given array A[] of size N (1 &lt;= N &lt;= 15), count all possible arrays formed by rearranging elements of A[] such that at least one of the following conditions is true for adjacent elements of that array: A[i] % A[i + 1] == 0A[i + 1] % A[i] == 0The count can be a large, modulo answer with 109+ 7 before printing. Examples: Input: A[] = {2, 3, 6}
11 min read
Find index of an extra element present in one sorted array
Given two sorted arrays. There is only 1 difference between the arrays. The first array has one element extra added in between. Find the index of the extra element. Examples: Input: {2, 4, 6, 8, 9, 10, 12}; {2, 4, 6, 8, 10, 12}; Output: 4 Explanation: The first array has an extra element 9. The extra element is present at index 4. Input: {3, 5, 7,
15+ min read