Number of substrings of one string present in other

By | September 25, 2023

Given 2 strings A and B, the task is to count the number of substrings of A which are also present in B.

Example:

Input: a="plu" b="Cplusplus" 
Output: 6 

Explanation: 
p, l, u, pl, lu, and plu are the 6 substrings of string a present in string b also.

Approach:
We will just run 2 loops and find every substring of string a and check if it’s present in string b or not.

Implementation in C++:

#include <bits/stdc++.h> 
using namespace std; 

int count(string a, string b)
{
	int count=0;
	int n=a.size();
	
	for(int i=1;i<=n;i++)
	{
	    for(int j=0;j<=n-i;j++)
	    {
	        string str=a.substr(j,i);
	        
	        int pos=b.find(str);
	        if(pos!=-1)
	            count++;
	           
	    }
	}
	return count;
}

int main()
{
	string a="plu", b="Cplusplus";
	cout<<count(a,b);
	return 0;
}

Output:

6

Time Complexity: O(n*n) = O(n^2)

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.