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.
Time Complexity : O(n)
- Longest Common Substring in an Array of Strings
- Check if there is any common character in two given strings
- Longest Common Substring | DP-29
- Number of common base strings for two strings
- Print the longest common substring
- SequenceMatcher in Python for Longest Common Substring
- Longest Common Substring (Space optimized DP solution)
- Longest common substring in binary representation of two numbers
- Common characters in n strings
- Count common subsequence in two strings
- Count common characters in two strings
- Interleaving of two given strings with no common characters
- LCS (Longest Common Subsequence) of three strings
- Longest common anagram subsequence from N strings
- Count the number of common divisors of the given strings
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.