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)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Longest Common Substring in an Array of Strings
- Check if there is any common character in two given strings
- Number of common base strings for two strings
- Longest Common Substring | DP-29
- Print the longest common substring
- SequenceMatcher in Python for Longest Common Substring
- Longest common substring in binary representation of two numbers
- Longest Common Substring (Space optimized DP solution)
- Common characters in n strings
- Count common characters in two strings
- Count common subsequence in two strings
- Interleaving of two given strings with no common characters
- LCS (Longest Common Subsequence) of three strings
- Count the number of common divisors of the given strings
- Longest common anagram subsequence from N strings
- Number of binary strings such that there is no substring of length ≥ 3
- Print common characters of two Strings in alphabetical order
- Meta Strings (Check if two strings can become same after a swap in one string)
- Find the longest common prefix between two strings after performing swaps on second string
- Python code to print common characters of two Strings in alphabetical order
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.