Check if two strings have a common substring
You are given two strings str1 and str2. You have to check if the two strings share a common substring.
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.
# 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 =  * (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
Time Complexity : O(n)