Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Check if there is any common character in two given strings
Next article icon

Check if two strings have a common substring

Last Updated : 27 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given two strings str1 and str2. You have to check if the two strings share a common substring.

Examples : 

Input : str1 = "HELLO"         str2 = "WORLD" Output : YES Explanation :  The substrings "O" and "L" are common to both str1 and str2  Input : str1 = "HI"         str2 = "ALL" Output : NO Explanation : Because str1 and str2  have no common substrings

A basic approach runs in O(n^2), where we compare every character of string 1 with every character of string 2 and replace every matched character with a "_" and set flag variable as true.

An efficient approach works in O(n). We basically need to check if there is a common character or not. We create a vector of size 26 for alphabets and initialize them as 0. For every character in string 1 we increment vector index of that character eg: v[s1[i]-'a']++, for every character of string 2 we check vector for the common characters if v[s2[i]-'a'] > 0 then set flag = true and v[s2[i]-'a']-- such that one character of string 2 is compared with only one character of string 1.

Implementation:

C++
// CPP program to check if two strings have // common substring #include <bits/stdc++.h> using namespace std;  const int MAX_CHAR = 26;  // function to return true if strings have  // common substring and no if strings have // no common substring bool twoStrings(string s1, string s2) {    // vector for storing character occurrences   vector<bool> v(MAX_CHAR, 0);    // increment vector index for every   // character of str1   for (int i = 0; i < s1.length(); i++)     v[s1[i] - 'a'] = true;    // checking common substring of str2 in str1   for (int i = 0; i < s2.length(); i++)      if (v[s2[i] - 'a'])         return true;     return false;         }  // driver program int main() {   string str1 = "hello";   string str2 = "world";   if (twoStrings(str1, str2))      cout << "Yes";   else      cout << "No";   return 0; } 
Java
// Java program to check if two strings have // common substring import java.util.Arrays;  class GFG {     static int MAX_CHAR = 26;          // function to return true if strings have      // common substring and no if strings have     // no common substring     static boolean twoStrings(String s1, String s2)      {         // vector for storing character occurrences         boolean v[]=new boolean[MAX_CHAR];         Arrays.fill(v,false);              // increment vector index for every         // character of str1         for (int i = 0; i < s1.length(); i++)             v[s1.charAt(i) - 'a'] = true;                  // checking common substring of str2 in str1         for (int i = 0; i < s2.length(); i++)              if (v[s2.charAt(i) - 'a'])              return true;                  return false;          }          // Driver code     public static void main (String[] args)      {         String str1 = "hello";         String str2 = "world";         if (twoStrings(str1, str2))             System.out.print("Yes");         else             System.out.print("No");     } }  // This code is contributed by Anant Agarwal. 
Python3
# Python3 code to implement the approach  # python program to check if two strings have # common substring MAX_CHAR = 26  # function to return true if strings have  # common substring and no if strings have # no common substring def twoStrings(s1, s2):      # vector for storing character occurrences     v = [0 for i in range(MAX_CHAR)]      # increment vector index for every     # character of str1     for i in range(len(s1)):         v[ord(s1[i]) - ord('a')] = True      # checking common substring of str2 in str1     for i in range(len(s2)):         if v[ord(s2[i]) - ord('a')]:             return True     return False  # driver program str1 = "hello" str2 = "world" if twoStrings(str1, str2):     print("Yes") else:     print("No")  # This code is contributed by phasing17 
C#
// C# program to check if two  // strings have common substring using System;  class GFG {     static int MAX_CHAR = 26;          // function to return true if strings have      // common substring and no if strings have     // no common substring     static bool twoStrings(String s1, String s2)      {         // vector for storing character occurrences         bool []v = new bool[MAX_CHAR];              // Arrays.fill(v,false);     for(int i = 0; i < MAX_CHAR; i++)     v[i]=false;              // increment vector index for          // every character of str1         for (int i = 0; i < s1.Length; i++)             v[s1[i] - 'a'] = true;                  // checking common substring of str2 in str1         for (int i = 0; i < s2.Length; i++)              if (v[s2[i] - 'a'])              return true;                  return false;          }          // Driver code     public static void Main ()      {         String str1 = "hello";         String str2 = "world";         if (twoStrings(str1, str2))             Console.Write("Yes");         else             Console.Write("No");     } }  // This code is contributed by nitin mittal. 
JavaScript
<script>  // javascript program to check if two strings have // common substring  var MAX_CHAR = 26;  // function to return true if strings have  // common substring and no if strings have // no common substring function twoStrings(s1, s2) {    // vector for storing character occurrences   var v = Array(MAX_CHAR).fill(0);    // increment vector index for every   // character of str1   for (var i = 0; i < s1.length; i++)     v[s1[i] - 'a'] = true;    // checking common substring of str2 in str1   for (var i = 0; i < s2.length; i++)      if (v[s2[i] - 'a'])         return true;     return false;         }  // driver program var str1 = "hello"; var str2 = "world"; if (twoStrings(str1, str2))    document.write( "Yes"); else    document.write("No");  // This code is contributed by rutvik_56. </script>  

Output
Yes

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


Next Article
Check if there is any common character in two given strings

S

Shivam.Pradhan
Improve
Article Tags :
  • Strings
  • DSA
  • cpp-vector
  • frequency-counting
Practice Tags :
  • Strings

Similar Reads

  • Number of common base strings for two strings
    Given two strings s1 and s2, we need to find number of common base strings of two. A substring of a string s is called base string if repeated concatenation of the substring results in s. Examples: Input : s1 = "pqrspqrs" s2 = "pqrspqrspqrspqrs" Output : 2 The two common base strings are "pqrs" and
    6 min read
  • Check if there is any common character in two given strings
    Given two strings. The task is to check that is there any common character in between two strings. Examples: Input: s1 = "geeksforgeeks", s2 = "geeks" Output: Yes Input: s1 = "geeks", s2 = "for" Output: No Approach: Traverse the 1st string and map the characters of the string with its frequency, in
    8 min read
  • Check if String Contains Substring in Python
    This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
    8 min read
  • Check if a string is substring of another
    Given two strings txt and pat, the task is to find if pat is a substring of txt. If yes, return the index of the first occurrence, else return -1. Examples : Input: txt = "geeksforgeeks", pat = "eks"Output: 2Explanation: String "eks" is present at index 2 and 9, so 2 is the smallest index. Input: tx
    8 min read
  • Count common subsequence in two strings
    Given two string S and T. The task is to count the number of the common subsequence in S and T. Examples: Input : S = "ajblqcpdz", T = "aefcnbtdi" Output : 11 Common subsequences are : { "a", "b", "c", "d", "ab", "bd", "ad", "ac", "cd", "abd", "acd" } Input : S = "a", T = "ab" Output : 1 To find the
    11 min read
  • Print the longest common substring
    Given two strings ‘X’ and ‘Y’, print the length of the longest common substring. If two or more substrings have the same value for the longest common substring, then print any one of them. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx"
    15+ min read
  • Queries to check if string B exists as substring in string A
    Given two strings A, B and some queries consisting of an integer i, the task is to check whether the sub-string of A starting from index i and ending at index i + length(B) - 1 equals B or not. If equal then print Yes else print No. Note that i + length(B) will always be smaller than length(A). Exam
    15+ min read
  • Check if a string is concatenation of another given string
    Given two strings str1 and str2 of length N and M respectively, the task is to check if the string str1 can be formed by concatenating the string str2 repetitively or not. Examples: Input: str1 = “abcabcabc”, str2 = “abc”Output: YesExplanation: Concatenating the string str2 thrice generates the stri
    7 min read
  • Check if the string has a reversible equal substring at the ends
    Given a string S consisting of N characters, the task is to check if this string has a reversible equal substring from the start and the end. If yes, print True and then the longest substring present following the given conditions, otherwise print False. Example: Input: S = "abca"Output: TrueaExplan
    5 min read
  • Javascript Program To Check If A String Is Substring Of Another
    Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :  Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences