Check if two strings have a common substring - GeeksforGeeks

19 Apr, 2022
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. 
C++
Java
C#
Javascript
// 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 substringbool 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 programint main() {  string str1 = "hello";  string str2 = "world";  if (twoStrings(str1, str2))     cout << "Yes";  else     cout << "No";  return 0;}
// Java program to check if two strings have// common substringimport 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.
Python 3 

# Python 3 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] * (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 Code
if __name__ == "__main__":
    str1 = "hello"
    str2 = "world"
    if (twoStrings(str1, str2)):
        print("Yes")
    else:
        print("No")

# This code is contributed 
# by ChitraNayal


// C# program to check if two// strings have common substringusing 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.
<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 substringfunction 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 programvar 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)  
YouTubeGeeksforGeeks507K subscribersCheck if two strings have a common substring | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ZdRMhgCuk3k" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
nitin mittal
ukasp
rutvik_56
sagartomar9927
cpp-vector
frequency-counting
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews